@Directive v/s @Component in Angular
What is the difference between @Component
and @Directive
in Angular? Both of them seem to do the same task and have the same attributes.
What are the use cases and when to prefer one over another?
A @Component requires a view whereas a @Directive does not.
Directives
I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A'
(Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.
import {Directive} from '@angular/core';
@Directive({
selector: "[logOnClick]",
hostListeners: {
'click': 'onClick()',
},
})
class LogOnClick {
constructor() {}
onClick() { console.log('Element clicked!'); }
}
Which would be used like so:
<button logOnClick>I log when clicked!</button>
Components
A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:
import {Component, View} from '@angular/core';
@Component({
selector: 'contact-card',
template: `
<div>
<h1>{{name}}</h1>
<p>{{city}}</p>
</div>
`
})
class ContactCard {
@Input() name: string
@Input() city: string
constructor() {}
}
Which would be used like so:
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
ContactCard
is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.
In summary
Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.
Sources:
Components
@Component
meta-data annotation. @View
decorator or templateurl template are mandatory in the component. Directive
@Directive
meta-data annotation. Sources:
http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html
组件是一个模板指令,而@Component
装饰器实际上是一个@Directive
装饰器,扩展了模板导向的特性。