Angular 6: How to randomly display an element (Math.random() inside *ngIf)

Viewed 1778

Inside an *ngFor loop, I want an HTML element to randomly display itself...50/50 chance.

Here is what I thought would work:

<span *ngIf="Math.random() < 0.5">test</span>

But I get error:

BookingPageComponent.html:139 ERROR TypeError: Cannot read property 'random' of undefined

What am I doing wrong and how should it be done correctly?

Thanks!

3 Answers

Math class is not available on evaluated expressions, but are available inside your component class.

So you can create a method:

public showRandomly(bias) {
    return Math.rand() < bias;
}

Then use it in your ngIf:

<span *ngIf="showRandomly (0.5)">test</span>

Note that this random will run every view refresh and might not give you the expected result.

you can't run that in the template. You can call a function in your component that calls Math.Random

example:

<span *ngIf="randomMath() < 0.5">test</span>

in your component:

randomMath() { return Math.random() }

Math class is not available natively on expression but you can do like that in your TS file: simply write

Math: Math = Math;

and you keep your template

<span *ngIf="Math.random() < 0.5">test</span>

But it's recommanded to add a new function like below:

<span *ngIf="isVisible()">test</span>

In your TS file:

ifVisible(): boolean{
    return Math.random() < 0.5; 
}
Related