循环遍历一个数组,在一个时间间隔内只显示一个内容索引(Angular 2+)
Looping through an array and display only one index of content in a time interval (Angular 2+)
我正在尝试找到在 Angular 2+ 中循环遍历数组并且每 10 秒仅显示一次数组数据的最佳方法
例如
phrase = ["Hello", "Yo", "Whats up?"];
<div *ngFor = "let p of phrase">
{{p}}
<div>
一段时间后显示 "Hello" 然后删除 "Hello" 然后显示 "Yo" 等等。
显然有很多方法可以做到这一点,但您可以使用例如 rxjs
中的 interval()
:
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
使用javascriptsetInterval
方法代替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)
}
}
我正在尝试找到在 Angular 2+ 中循环遍历数组并且每 10 秒仅显示一次数组数据的最佳方法
例如
phrase = ["Hello", "Yo", "Whats up?"];
<div *ngFor = "let p of phrase">
{{p}}
<div>
一段时间后显示 "Hello" 然后删除 "Hello" 然后显示 "Yo" 等等。
显然有很多方法可以做到这一点,但您可以使用例如 rxjs
中的 interval()
:
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
使用javascriptsetInterval
方法代替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)
}
}