【问题标题】:Display item in ngFor with some delay in Angular 5在 ngFor 中显示项目,在 Angular 5 中有一些延迟
【发布时间】:2018-08-08 14:21:33
【问题描述】:

我有一个场景,其中我有一个在运行时填充的数组,我想通过 ngFor 循环在 HTML 模板中显示它的元素,但有一些延迟。 (即显示第一项,然后延迟第二项,依此类推。

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

我需要延迟后生成每个 li。

【问题讨论】:

  • 你能添加你的代码吗
  • Chellappan,我已经添加了我的代码。
  • @AhmerKhan 我希望这是个玩笑...添加您尝​​试过的内容,而不是...
  • 不管怎样,关于你的要求,考虑一个一个推送项目,或者使用角度动画。

标签: angular ngfor


【解决方案1】:

这行得通:

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

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

DEMO

【讨论】:

  • 很好,很简单....想不到这个。不知道为什么,但我宁愿使用clearInnterval() 然后返回..
  • 这行得通..但由于它附加到数组中,它会在循环中呈现 for 并闪烁我的整个屏幕,而且每个 ngfor 都会为我创建执行 api 调用的模块.. 这可能不起作用对我来说哈哈
【解决方案2】:

Angular 实现的animations 有很多,可以应用于ngFor

可以直接看demo:

https://stackblitz.com/edit/angular-list-animations?file=app%2Fapp.component.html

例如一个动画ease-in

组件

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%)'
      }))
    ])
  ])
]

然后,在 HTML 中

<ul>
 <li *ngFor="let x of array" [@flyInOut]="'in'">{{x.name}}</li>
</ul>

【讨论】:

    【解决方案3】:

    现在,我只能想到这个解决方案,创建一个 tempArray 每隔一秒填充一次。我写了一个递归函数,它每隔一秒调用一次,基本条件是检查循环索引是否大于或等于实际数组长度

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

    【讨论】:

      【解决方案4】:

      只需更改 setInterval 的 setTimeout 并添加 this.Array2.pop() 即可在一段时间后获得新值

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

      【讨论】:

        猜你喜欢
        • 2020-09-25
        • 2019-01-09
        • 2019-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-17
        • 1970-01-01
        相关资源
        最近更新 更多