What is the difference between @Component and @Directive in Angular?
What is the difference between @Component and @Directive in Angular?
In Angular, @Component
and @Directive
are both decorators used to define classes that extend the functionality of HTML elements in an Angular application. However, they serve distinct purposes and are used in different scenarios.
@Component
is used to define a component, which is essentially a directive with a template. This means it not only contains application logic but also has an associated view defined by HTML templates. Components are the primary building blocks of Angular applications, used to create reusable UI elements that encapsulate functionality including the view, data bindings, and behavior.
Key characteristics of @Component
include:
An example of a component might look like this:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
title = 'Hello World';
}
@Directive
, on the other hand, is used to add behavior to existing DOM elements or existing components. It does not involve a template of its own, making it suitable for adding functionalities such as changing appearance, responding to user interactions, or manipulating the DOM.
Key characteristics of `@Dire...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào