ngFor Structural Directive
ngFor
directive is used to repeat a DOM or HTML element for a given item in array or collection.
The syntax is
*ngFor="let item of items"
Let's write some code to check how powerful is ngFor
built in directive of angular.
Create new Angular App
ng new NgForDemo
cd NgForDemo
Open project to edit
Open the project in Visual Studio Code by entering command code .
Serve or run the application
Run the application on port 8000
ng serve --port 8000
Test the application
Open your browser and goto to url http://localhost:8000
and check your application running.
Write some hard values in app.component.ts
goto src\app\app.component.ts
and enter the data below.
export class AppComponent {
stringArray: string[];
objectArray: Object[];
complexObjectArray: Object;
constructor() {
this.stringArray = ['India', 'Afgan', 'New York'];
this.objectArray = [
{ name: 'Nisar', mark: 35, city: 'India' },
{ name: 'John', mark: 12, city: 'Afgan' },
{ name: 'Amy', mark: 22, city: 'New York' }
];
this.complexObjectArray = [
{
city: 'India',
people: [
{ name: 'Amy', mark: 12 },
{ name: 'Lisa', mark: 22 }
]
},
{
city: 'Afgan',
people: [
{ name: 'John', mark: 35 },
{ name: 'Mary', mark: 36 }
]
}
];
};
}
Repeat Simple Array of String
Go to src\app\app.component.html
file and update the html
<h1>
Simple String
</h1>
<li *ngFor="let str of stringArray">
{{str}}
</li>
This will product following output
Repeat Array of Object
In same app.component.html
file update the html
<h1>Array of Object</h1>
<table border="1px">
<thead>
<tr>
<th>Name</th>
<th>Mark</th>
<th>City</th>
</tr>
</thead>
<tr *ngFor="let arr of objectArray">
<td>{{ arr.name }}</td>
<td>{{ arr.mark }}</td>
<td>{{ arr.city }}</td>
</tr>
</table>
This produce output
Array of Nested Object
<h1>Array of Nested Object</h1>
<div *ngFor="let item of complexObjectArray">
<h2>{{ item.city }}</h2>
<table border="1px" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tr *ngFor="let p of item.people">
<td>{{ p.name }}</td>
<td>{{ p.mark }}</td>
</tr>
</table>
</div>
This ngFor
produce the output
Track index of array in ngFor
<li *ngFor="let str of stringArray; let num= index">
{{num+1}} {{str}}
</li>