Angular 8 *ngFor Directive
Angular 8 ngFor Directive
The *ngFor directive is used to repeat to repeat a portion of HTML template once per each item from an iterable list (collection). The ngFor is an Angular structural directive and is similar to ngRepeat in AngularJS. Some local variables like Index, First, Last, odd and even are exported by *ngFor directive.
Syntax of ngFor
How to use ngFor Directive?
To use ngFor Directive, we have to create a block of HTML elements, which can display a single item of the items collection. After that, we can use the ngFor Directive to tell angular to repeat that block of HTML elements for each item in the list.
The ngFor Directive has a different syntax from other directives we've seen. If we familiar with the ngFor statement, we will notice that they are identical.
Example for *ngFor Directive
Firstly, we have to create angular Application. After that, open the app.component.ts and add the following code.
The following code contains a list of Top 3 movies in a movies array. Let’s build a template to display these movies in a tabular form.
import { Component } from '@angular/core'; @Component({ selector: 'movie-app', templateUrl:'./app/app.component.html', styleUrls:['./app/app.component.css'] }) export class AppComponent { title: string ="Top 10 Movies" ; movies: Movie[] =[ {title: 'Winter Is Coming',director: 'Tim Van Patten',cast:'Idris Elba, Ginnifer Goodwin, Jason Bateman',releaseDate:'March 4, 2016'}, {title:'Batman v Superman: Dawn of Justice',director:'Zack Snyder',cast: 'Ben Affleck, Henry Cavill, Amy Adams',releaseDate:'March 25, 2016'}, {title:'Captain America: Civil War',director:'Anthony Russo, Joe Russo',cast:' Scarlett Johansson, Elizabeth Olsen, Chris Evans',releaseDate:' May 6, 2016'}, {title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer Lawrence, Olivia Munn, Oscar Isaac',releaseDate:'May 27, 2016'}, ] } class Movie { title : string; director : string; cast : string; releaseDate : string; }
Now, open the app.component.html and add the following code:
{{title}}
Title | Director | Cast | Release Date |
---|---|---|---|
{{movie.title}} | {{movie.director}} | {{movie.cast}} | {{movie.releaseDate}} |