Directives can be used to manipulate DOM element. It's so useful when you wanna make a custom (third party) directive that can be used by other programmers in your team or world.
Basically there are three types of directives.
1) Structural Directive
2) Attribute directives
3) Component Directive(with template)
1) Structural Directives usually manipulates structure of view/template. Eg. *ngFor will generate element according to your list count. *ngIf will display/hide view according to passed value.
2) Attribute directive allows you to add an attribute on DOM element and then you can do many things with that DOM element.
eg.
<p myColor >Color me!</p> //<<< this helps you to grab DOM element using ElementRef and then I'll color it as shown below.
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[myColor]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
here myColor is just an attribute directive as it is added to the DOM element as an attribute but this attribute doesn't accept any value yet.
Now let's add a value to myColor attribute,
<p [myColor]="color">Highlight me!</p>
@Input : Here we are passing
color variable(Angular2 bindings) so in directive we must have a mechanism to receive it. So we should use
@Input API as we are going to get value from parent component(you can consider directive as a child of parent)
@Output : If you want directive to emit some value that should be received by parent component then you should use
@Output API