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

Categories

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

angular - What is the difference between [ngFor] and [ngForOf] in angular2?

As per my understanding, Both are doing the same functions. But,


Is my understanding is correct? or Could you please share more difference's(details) about ngFor and ngForOf?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

ngFor and ngForOf are not two distinct things - they are actually the selectors of the NgForOf directive.

If you examine the source, you'll see that the NgForOf directive has as its selector: [ngFor][ngForOf] , meaning that both attributes need to be present on an element for the directive to 'activate' so to speak.

When you use *ngFor, the Angular compiler de-sugars that syntax into its cannonical form which has both attributes on the element.

So,

  <div *ngFor="let item of items"></div>

desugars to:

 <template [ngFor]="let item of items">
     <div></div>
 </template>

This first de-sugaring is due to the '*'. The next de-sugaring is because of the micro syntax: "let item of items". The Angular compiler de-sugars that to:

 <template ngFor let-item="$implicit" [ngForOf]="items">
   <div>...</div>
 </template>

(where you can think of $implicit as an internal variable that the directive uses to refer to the current item in the iteration).

In its canonical form, the ngFor attribute is just a marker, while the ngForOf attribute is actually an input to the directive that points to the the list of things you want to iterate over.

You can check out the Angular microsyntax guide to learn more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...