Angular 6:如何随机显示一个元素(*ngIf 内的 Math.random())

J B*_*min 2 angular

在 *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)

我做错了什么,应该如何正确完成?

谢谢!

Eli*_*res 5

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)

请注意,此随机将在每次视图刷新时运行,并且可能不会给您预期的结果。