The ever-so-useful NgForOf

Every templating language has constructs that allow the templating engine to generate HTML (by repetition). Angular has NgForOf. The NgForOf directive is a super useful directive used to duplicate a piece of an HTML fragment n number of times. Let's again look at how we have used NgForOf in the video player:

<div *ngFor="let video of safeVideoUrls"> 
   <iframe width="198" height="132" [src]="video" frameborder="0" allowfullscreen></iframe> 
</div>
The directive selector for NgForOf is {selector: '[ngFor][ngForOf]'}, so we can use either ngFor or ngForOf in the view template. We also at times refer to this directive as ngFor.

The preceding code repeats the div fragment for each exercise video (using the safeVideoUrls array). The let video of safeVideoUrls string expression is interpreted as follows: take each video in the safeVideoUrls array and assign it to a template input variable, video.

This input variable can now be referenced inside the ngFor template HTML, as we do when we set the src property binding.

Interestingly, the string assigned to the ngFor directive is not a typical Angular expression. Instead, it's a microsyntax—a micro language, which the Angular engine can parse.


You can learn more about microsyntax in Angular's developer guide: http://bit.ly/ng6be-micro-syntax.

This microsyntax exposes a number of iteration context properties that we can assign to template input variables and use them inside the ngFor HTML block.

One such example is index. index increases from 0 to the length of the array for each iteration, something similar to a for loop, in any programming language. The following example shows how to capture it:

<div *ngFor="let video of videos; let i=index"> 
     <div>This is video - {{i}}</div> 
</div> 

Other than index, there are some more iteration context variables; these include first, last, even, and odd. This context data allows us to do some nifty stuff. Consider this example:

<div *ngFor="let video of videos; let i=index; let f=first"> 
     <div [class.special]="f">This is video - {{i}}</div> 
</div> 

It applies a special class to the first video div.

The NgForOf directive can be applied to HTML elements as well as our custom components. This is a valid use of NgForOf:

<user-profile *ngFor="let userDetail of users" [user]= "userDetail"></user-profile>

Always remember to add an asterisk (*) before ngFor (and other structural directives). * has a significance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset