Component v/s Directive
This blog explains difference between Component and Directive in Angular2.
In Angular1.X we use directive for below reasons:
- To add behavior to an existing DOM element.
- To create a component with attached behaviour.
Angular2 has introduced two different meta-data annotation for these, first is @Directive, which is used to add behaviour to an existing element. Second is @Component, which is used to create a component with attached behaviour. For more differences and examples have a look at the points below:
We create Component with the help of @Component meta-data annotation while we create Directive with the help of @Directive meta-data annotation.
@Component is used to create new View(Shadow DOM) with attached behaviour while @Directive is used to add behavior to an existing DOM element.
With the help of @Component we can break our application into smaller components, and can do component based development while with the help of @Directive we can attach different behaviours to an existing DOM element or different existing DOM element.
@Component is used to create reusable components while @Directive is used to create reusable behaviour.
-
@Component requires a view via @View or template/url while @Directive does not.
@View or template/url is mandatory in the component.
-
Example:
@Component
import {Component} from '@angular/core'; import {EnterDirective} from "./sample.directive"; @Component({ selector: 'sample-component', template: ` <strong>Hello World</strong> form <strong>{{name}} Component</strong>! <br/> <input type="text" (enter)="enterHandler($event)" > `, directives: <any>[EnterDirective] }) export class SampleComponent { name:string = 'Sample'; enterHandler(event) { console.log(event); } }
@Directive
import {Directive, Output} from "@angular/core"; import {EventEmitter} from "@angular/common/src/facade/async"; @Directive({ selector: '[enter]', host: { '(keypress)': 'enterHandler($event)' } }) export class EnterDirective { @Output() enter = new EventEmitter<any>(); constructor() { } enterHandler(event) { if (event.keyCode == 13) { this.enter.emit(event); } } }
Communication between Component and Directive can be done same way as we do between two Components.