在 *ngFor 循环中,我想要一个 HTML 元素随机显示自己...50/50 的机会。
这是我认为可行的方法:
<span *ngIf="Math.random() < 0.5">test</span>
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
BookingPageComponent.html:139 ERROR TypeError: Cannot read property 'random' of undefined
Run Code Online (Sandbox Code Playgroud)
我做错了什么,应该如何正确完成?
谢谢!
Math class 在计算表达式上不可用,但在您的组件类中可用。
所以你可以创建一个方法:
public showRandomly(bias) {
return Math.rand() < bias;
}
Run Code Online (Sandbox Code Playgroud)
然后在你的 ngIf 中使用它:
<span *ngIf="showRandomly (0.5)">test</span>
Run Code Online (Sandbox Code Playgroud)
请注意,此随机将在每次视图刷新时运行,并且可能不会给您预期的结果。
| 归档时间: |
|
| 查看次数: |
1239 次 |
| 最近记录: |