Hi I m reading a book about angular
I got the following sentence dipicted below
For me it is entuitive that the ngFor is a structural directive. But where is the second one ?
Thanks
See Question&Answers more detail:osHi I m reading a book about angular
I got the following sentence dipicted below
For me it is entuitive that the ngFor is a structural directive. But where is the second one ?
Thanks
See Question&Answers more detail:osThere 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