Angular *ngFor is made of one single structural Directive? Or two?

Viewed 330

While I was answering another question, I saw a screenshot of a book that states that *ngFor (syntactic sugar version) is made of two structural directives.

This is the code shown in the book:

<ul>
    <li *ngFor="let book of books">
        {{book.title}}
    </li>
</ul>

So either the Angular guide is wrong when it states that "Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name...". Or the book is wrong. Because I see only one asterisk there.

So I started digging in the ngFor docs of Angular. And I've found this:

enter image description here

From this screenshot, it seems that the author of the book is right, that [ngFor] and [ngForOf] are both (structural) directives.

So now I am thinking about this scenario. Maybe it's like two (structural) directives:

  1. the first one that is responsible for copying the entire HTML element and place inside the ng-template tag (since in Angular you can only use one structural directive for each element)
  2. the second that is responsible for copying the element inside ng-template as many time as it needs to be iterated and hydrating the elements with the required data

This is a screenshot of the book that I am talking about: screenshot of a book that states that *ngFor is made by two structural directives

I am sorry, but I don't have any details myself about the name of the book or the author (as they are not included by the original author of the question).

1 Answers

The Angular docs clearly states that only one structural directive may be used:

You may apply only one structural directive to an element

It's also might be helpful to understand the difference between an attribute directive and a structural directive:

  1. Structual directives change the DOM layout by adding/removing DOM elements, while attribute directives only change the appearance or behavior of an element.

  2. Structual directives change the structure of the view, while attribute directives are used as attributes of an element.

  3. Structural directives are used after * like *ngIf or *ngFor while directives just use the the normal attributes syntax like this: ngStyle.

So to answer your question, the code snippet uses one structural directive. Not sure why the author said two, but as a rule of thumb if two sources collide, chances are the correct one is the official docs.

More info:

Directives Overview - Angular Docs

Related