[英]Angular NgFor Loop Through Array Object with Delay for Each Item
我在UI上工作,雲在屏幕上水平移動。
我有一個要在雲上顯示的項目數組,該數組的每個項目都是一個雲。 該組件具有CSS顯示絕對位置,因此我當前的方法是在彼此之上創建一堆組件。 我的目標是一次加載4000ms的延遲,而不是一次加載數組的項目。 我知道我們可能需要在cloud.component.ts或html模板* ngFor中使用setTimeout()或setInterval()。
我嘗試了*ngFor="let setTimeout(() => item, 4000) of items"
但似乎不正確。
下面是我的組件的結構
cloud.component.ts
export class CloudComponent {
@Input('cloud') public element: {
....
// not important
}
}
clouds.component.html
<app-cloud *ngFor="let item of items" [cloud]="item"></app-cloud>
clouds.component.ts
export class CloudsComponent {
public clouds: Cloud[] = [item,item,item,item,item]
// service call
}
您可以在組件中進行所有設置,然后使用setInterval()
加載它們,然后殺死,然后在setInterval()
結束時銷毀它。
dummyItems=[];
index = 1;
public clouds: Cloud[] = [item,item,item,item,item]
ngOnInit() {
if( this.coulds[0]) {
this.dummyItems.push(this.clouds[0]);
}
this.timer = setInterval(() => {
if (this.index < this.coulds.length) {
this.dummyItems.push(this.clouds[index]);
this.index++;
} else {
clearInterval(this.timer); // this is optional but good practice
}
}, 4000)
}
您必須以4000毫秒的超時將當前數組輸入到虛擬數組中。
this.dummyItems=[]
for(let i = 0; i < this.items.length; i++){
let item = this.items[i];
setTimeout(() => {
this.dummyItems.push(item);
}, 4000*(i+1));
}
在模板中,
<app-cloud *ngFor="let item of dummyItems" [cloud]="item"></app-cloud>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.