Display item in ngFor with some delay in Angular 5

Clash Royale CLAN TAG#URR8PPP
Display item in ngFor with some delay in Angular 5
I have a scenario in which I have an array that filled at the run-time, I want to show its elements in HTML template via ngFor loop with some delay. (i.e display first item, then after some delay second item and so on.
<ul>
<li *ngFor="let x of array">x.name</li>
</ul>
this.selectedArray = ;
getArrayValues(index)
this.Array2.forEach(e =>
setTimeout(() =>
this.selectedArray.push(e);
, 1000);
)
I need every li to be generated after some delay.
Chellappan, I have added my code.
– Ahmer Khan
Aug 8 at 14:26
@AhmerKhan I hope this is a joke ... Add what you have tried, not that ...
– trichetriche
Aug 8 at 14:26
Anyway, about your request, consider either pushing items one by one, or using angular animations.
– trichetriche
Aug 8 at 14:26
4 Answers
4
this works:
ngOnInit()
this.getArrayValues(0);
getArrayValues(index)
setInterval(() =>
if(index == this.Array2.length)
return;
this.selectedArray.push(this.Array2[index]);
index++;
, 1000);
DEMO
Nice, way easy.... couldn't think of this. Don't know why but I ould rather use
clearInnterval() and then return..– Ashish Ranjan
Aug 8 at 15:12
clearInnterval()
There is a lot of animations available implemented by Angular which can be applied to ngFor
Angular
ngFor
You can see the demo direct:
https://stackblitz.com/edit/angular-list-animations?file=app%2Fapp.component.html
For example, an animation ease-in
ease-in
Component
animations: [
trigger('flyInOut', [
state('in', style(opacity: 1, transform: 'translateX(0)')),
transition('void => *', [
style(
opacity: 0,
transform: 'translateX(-100%)'
),
animate('0.2s ease-in')
]),
transition('* => void', [
animate('0.2s 0.1s ease-out', style(
opacity: 0,
transform: 'translateX(100%)'
))
])
])
]
then, in HTML
<ul>
<li *ngFor="let x of array" [@flyInOut]="'in'">x.name</li>
</ul>
Right now, I could only think of this solution, create a tempArray which populates in every second interval. I have written a recursive function which calls itself after every one second, the base condition is to check if the looping index is greater than or equal to the actual array length
<ul>
<li *ngFor="let x of tempArray">x.name</li>
</ul>
arr = [1,2,3];
tempArr =
function delayMe(index, tempArr)
if (index >= arr.length)
return;
(new Promise(resolve => setTimeout(resolve, 1000))).then(() =>
tempArr.push(arr[index]);
console.log(tempArr);
delayMe(index + 1, tempArr)
)
delayMe(0, tempArr);
Just change setTimeout for setInterval and add this.Array2.pop() to get new value after some time
setInterval
this.Array2.pop()
setInterval(() =>
this.selectedArray.push(this.Array2.pop());
, 1000);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
can you add your code
– Chellappan
Aug 8 at 14:21