Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

angular - Where is the second directive in this book statement

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...