Ahmer Khan
Ahmer Khan

Reputation: 767

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.

Upvotes: 1

Views: 4365

Answers (4)

Abdul Rafay
Abdul Rafay

Reputation: 3391

this works:

  ngOnInit() {
    this.getArrayValues(0);
  }

  getArrayValues(index) {
    setInterval(() => {
      if(index == this.Array2.length)
        return;
      this.selectedArray.push(this.Array2[index]);
      index++;
    }, 1000);
  }

DEMO

Upvotes: 4

Antoine V
Antoine V

Reputation: 7204

There is a lot of animations available implemented by Angular which can be applied to 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

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>

Upvotes: 2

Abel Valdez
Abel Valdez

Reputation: 2408

Just change setTimeout for setInterval and add this.Array2.pop() to get new value after some time

  setInterval(() => {
    this.selectedArray.push(this.Array2.pop());
  }, 1000);

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

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);

Upvotes: 0

Related Questions