Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I m reading a book about angular

I got the following sentence dipicted below

enter image description here

For me it is entuitive that the ngFor is a structural directive. But where is the second one ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

  1. 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";
       }
     }
    
  2. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...