在Angular 4中,你可以使用以下代码来实现在模板中随机从数组中设置一个字符串值,并在两秒后更改为另一个字符串:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
strings: string[] = ['String 1', 'String 2', 'String 3'];
currentString: string;
ngOnInit() {
this.setCurrentString();
}
setCurrentString() {
this.currentString = this.strings[Math.floor(Math.random() * this.strings.length)];
setTimeout(() => {
this.setCurrentString();
}, 2000);
}
}
{{ currentString }}
这样,每两秒钟,当前字符串值就会随机从数组中选择一个,并在两秒后更改为另一个字符串。