@Directive vs @Component in Angular.js
@Directive and @Component both does the same task and has the same attributes in the first look but their are some differences. Directives add behavior to an already existing DOM element or a component instance .import {Directive} from '@angular/core'; @Directive({ selector: "[logOnClick]", hostListeners: { 'click': 'onClick()', }, }) class LogOnClick { constructor() {} onClick() { console.log('Element clicked!'); } }
This would be used on:<button logOnClick>I log when clicked!</button>
Components When Directives adds behavior Component creates its own view with attached behaviour.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() {} }
It would be used on:<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
When you want to create reusable set of DOM elements of UI with custom behavior write a Component and write a directive to add reusable behavior to supplement existing DOM elements.
Comments
0 comments
Please Sign in or Create an account to Post Comments