The directive *ng For uses a iterator pattern to repeat any element and read the values from collection in a sequential order.
Angular iterations are provided with a set of properties that can access the iteration counter details which include the following
index--> It is a number Type
It returns the index number of iterator in an iteration.
It is a zero index based.
first--> It is boolean Type
It returns true if iteration counter is the first iterator
last--> It is boolean Type
It returns true if iteration counter is the last iterator
even--> It is boolean Type
It returns true for even occurances in iteration.
odd--> It is boolean Type
It returns true for odd occurances in iteration
trackBy -->It is a string(function)
It uses a function to track the changes in iteration.
Example
.ts File changes
import { Component } from '@angular/core';
@Component({
selector: 'app-iteration',
templateUrl: './iteration.component.html',
styleUrls: ['./iteration.component.css']
})
export class IterationComponent {
public products=[
{ Id:1, Name: 'Samsung Tv', Price:5600.44},
{ Id:2, Name: 'Sony Tv', Price:5900.44},
{ Id:3, Name: 'Mi Tv', Price:2600.44},
{ Id:4, Name: 'OnePlus Tv', Price:1600.44},
{ Id:5, Name: 'aiwa TV', Price:5600.44},
];
public Update() {
this.products=[
{ Id:6, Name: 'Onida TV', Price:3600.44},
];
}
}
.html File Changes
<h2> Iteration Properties</h2>
<div>
<button (click) ="Update()" > Update Products</button>
</div>
<table border="1" width="500">
<th> Product Id</th>
<th> Name </th>
<th> Price </th>
<th> Index</th>
<th> First </th>
<th> Last </th>
<th> Even </th>
<th> Odd </th>
<tr *ngFor="let item of products;
let i=index; let first=first;let last=last;let even=even;
let odd=odd">
<td> {{ item.Id}} </td>
<td> {{ item.Name}}</td>
<td> {{ item.Price}} </td>
<td> {{ i }} </td>
<td> {{ first }} </td>
<td> {{ last }} </td>
<td> {{ even }} </td>
<td> {{ odd }} </td>
</tr>
</table>
ScreenShot
appmodule.ts
index.html
Output:
On Clicking on update products
No comments:
Post a Comment
Thank you for visiting my blog