Roka545 Roka545 - 5 months ago 66
HTML Question

Check for null value in ngFor loop

I'm displaying information in buttons in my webpage. The buttons display several objects from a list and their fields (e.g. object.name, object.age, etc.). In some case, one of those fields are null. How can I go about checking if a value is null? If it's null, I would like to print 'Unknown' - as of now it prints nothing.

Here's is my ngFor loop (in my case, environment is sometimes null):

<button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary"
Name: {{object.name}} <br /> Locations: {{object.date}} <br /> Environments: {{object.environment}}
</button>


I know I can manually set environment to 'Unknown' since it is a string value, but I would like to know if there is a way to do this via html.

Answer

The pipe is a good solution but if you want you can use *ngIf directly in html:

<button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary"
    Name: <span *ngIf="object.name">{{object.name}}</span> <span *ngIf="!object.name">Unknown</span>