代码之家  ›  专栏  ›  技术社区  ›  Huy Le

角NgFor循环通过阵列对象,每个项目有延迟

  •  0
  • Huy Le  · 技术社区  · 7 年前

    我正在使用云在屏幕上水平移动的UI。

    我有一个要在云上显示的项目数组,数组中的每个项目都是一个云。组件具有css显示绝对位置,因此我当前的方法在彼此之上创建一个组件堆栈。我的目标不是一次加载数组的项,而是以4000ms的延迟加载每个项。我知道我们可能需要在clouds.component.ts或html模板*ngFor中使用setTimeout()或setInterval()。

    我试过了 *ngFor="let setTimeout(() => item, 4000) of items" 但似乎不对。

    下面是我的组件结构

    云.component.ts

    export class CloudComponent {
     @Input('cloud') public element: {
      ....
      // not important
     }
    }
    

    云.component.html

    <app-cloud *ngFor="let item of items" [cloud]="item"></app-cloud>
    

    云.component.ts

    export class CloudsComponent {    
     public clouds: Cloud[] = [item,item,item,item,item]
     // service call
    }
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   rhavelka    7 年前

    您可以在组件中设置所有内容,然后使用 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)
    }
    
        2
  •  0
  •   Helping hand    7 年前

    必须将当前数组馈送到具有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>
    
    推荐文章