Loops are used to iterate through objects or array, In angular we can use ngFor and For loop over array or object in angular, ngFor is a template structural directive which is used to iterate a loop in template file whereas for and each is used to iterate the loop in component. In angular or javascript we can use for loop in 3 types of for loop
in javascript or angular
for
– loops through a block of code a number of timesfor/in
– loops through the properties of an objectfor/of
loops through the values of an iterable object
and in angular template we can use ngFor
structural directive through the Array only, to iterate the object in angular template we need to use pipe keyvalue
.
Let’s take examples of for loops
ngFor loop iterate over Array or Object
In this example we will use ngFor structural directive in template html file as below
<div *ngFor="let item of [1,2,3,4]">
{{item}}
</div>
ngFor Loop iterate over Array key value
<div *ngFor="let item of [{id:1},{id:2}]">
{{item.id}}
</div>
ngFor Loop iterate over Array with index
<div *ngFor="let item of [{id:1},{id:2}]; let counter=index">
{{item.id}} {{counter}}
</div>
For loop over array or object using for-in, for-of and for
So in this example we will use loop with array, objects and block of code a number of times. As we have explained above loop can be used in three ways so here are examples
For loops through a block of code a number of times
for(let i=0 ;i<=5 ; i++){
console.log("value of i ",i);
}
For loops through a block of code a number of times
for(let i=0 ;i<=5 ; i++){
console.log("value of i ",i);
}
Output of above:
value of i 0 value of i 1 value of i 2 value of i 3 value of i 4 value of i 5
For-in loop on object
let items:any={id:1, name : 'test', }
for(let item in items){
console.log("value of item ",item,items[item]);
}
Output of above:
value of item id 1 value of item name test
For-of loop on object
let items:any={id:1, name : 'test', }
for(let item in items){
console.log("value of item ",item,items[item]);
}
Output of above:
value of item id 1 value of item name test
For-of loop on Array key value
let items:any=[{id:1, name : 'test'},{id:2, name : 'test2'}]
for(let item in items){
console.log("value of item ",item.id ,item.name);
}
Output of above:
value of item 1 test value of item 2 test2