【问题标题】:Looping through an array and display only one index of content in a time interval (Angular 2+)循环遍历数组并在时间间隔内仅显示一个内容索引(Angular 2+)
【发布时间】:2018-06-25 12:54:10
【问题描述】:

我正在尝试找到在 Angular 2+ 中循环遍历数组的最佳方法,并且仅每 10 秒显示一次数组的数据

例如

phrase = ["Hello", "Yo", "Whats up?"];

<div *ngFor = "let p of phrase">
 {{p}}
<div>

一段时间过去,显示“Hello”,然后删除“Hello”,然后显示“Yo”,依此类推。

【问题讨论】:

    标签: html angular loops intervals


    【解决方案1】:

    显然有很多方法可以做到这一点,但您可以使用例如 interval() from rxjs:

    import { Component } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable, interval } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Component({
      selector: 'hello',
      template: `
        {{ phrase[index$ | async] }}
      `,
    })
    export class HelloComponent {
      phrase = ["Hello", "Yo", "Whats up?"];
      index$: Observable<number>;
    
      constructor() {
        this.index$ = interval(1000).pipe(
          map((item, index) => index % this.phrase.length),
        )
      }
    }
    

    index$ 将每秒发出一个索引,告诉您使用phrase[index$ | async] 打印哪个短语。

    查看演示:https://stackblitz.com/edit/angular-qtmdxp?file=src%2Fapp%2Fhello.component.ts

    【讨论】:

      【解决方案2】:

      使用 javascript setInterval 方法而不是 ngfor

      phrase = ["Hello", "Yo", "Whats up?"];
      
      constructor(){ 
        this.timeOut();
      }
      
        timeOut(){
           let count = 0;
           setInterval(() => {
             if(count === this.phrase.length ){
               count = 0;
             }
             this.name = this.phrase[count]
             count++
           },1000)
        }
      }
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-26
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 1970-01-01
        • 2023-03-19
        • 2017-12-27
        相关资源
        最近更新 更多