There are indeed two types of directives.
1) Structural Directives
2) Attribute Directives
But in this example there is only one directive used and this is the *ngFor
. This is responsible for creating an li
element for every object of the books
array.
The attribute directive is a type of directive that can be applied to an existing element. This allows you to change the attributes of the element. Something like you can take the index at each iteration and then pass it into the attribute directive, and once based on a condition with the index you can format the li
element by changing its attributes such as the CSS Styling through the attribute directive.
I have attached an example use of the Attribute Directive
Directive Class
import { Directive, ElementRef, OnInit } from "@angular/core";
@Directive({
selector:'[appHighlight]'
})
export class HighlightText implements OnInit{
private theReference : ElementRef
constructor(theReference : ElementRef){
this.theReference = theReference;
}
ngOnInit(): void {
this.theReference.nativeElement.style.backgroundColor = "lightcoral";
}
}
Usage in Template
<p appHighlight>Directive Usage</p>
When the directive is referenced as an attribute using selector [appHighlight]
, in the element <p>
the attribute defined in the directive backgroundColor
in the OnInit
hook. You can change the attribute you want to change using the Renderer2
or by accessing the nativeElement
property, though it is recommended to use the Renderer2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…