Utilizing directives allows for the manipulation of DOM elements. This is particularly beneficial when creating custom directives that can be shared with other developers within your team or community.
There are primarily three categories of directives:
1) Structural Directives
2) Attribute Directives
3) Component Directives (with templates)
1) Structural Directives are typically used to alter the structure of a view or template. For instance, *ngFor
generates elements based on the number of items in a list, while *ngIf
controls the visibility of a view based on a provided condition.
2) Attribute Directives enable the addition of custom attributes to DOM elements, allowing for various manipulations to be performed on those elements.
For example:
<p myColor >Color me!</p> // This directive uses ElementRef to change the background color of the element to red.
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 an attribute directive
because it is added as an attribute to the DOM element, although it does not accept a value yet.
To assign a value to the myColor
attribute, you can do:
<p [myColor]="color">Highlight me!</p>
@Input: When passing a
color variable (Angular2 bindings)
to the directive, you must use the
@Input API
for receiving the value from the parent component (considering the directive as a child of the parent).
@Output: If the directive needs to emit a value to be received by the parent component, the
@Output API
can be utilized.