Let’s say I have config-items for my component. If they are available they should be in the output – otherwise not.
JavaScript
x
6
1
cfg = { name: "sam", address: "NY", age: 51 };
2
3
<p *ngIf="cfg.name != undefined">{{cfg.name}}</p>
4
<p *ngIf="cfg.address != undefined">{{cfg.address}}</p>
5
<p *ngIf="cfg.age != undefined">{{cfg.age}}</p>
6
The check for defined is pretty annoying if there are a lot of items.
Is there a way to do it better?
Advertisement
Answer
You can use the safe navigation operator (also known as optional chaining)
JavaScript
1
4
1
<p>{{cfg?.name}}</p>
2
<p>{{cfg?.address}}</p>
3
<p>{{cfg?.age}}</p>
4
Another option is to create a wrapping ng-container and apply the *ngIf
on it.
JavaScript
1
6
1
<ng-container *ngIf="cfg">
2
<p>{{cfg.name}}</p>
3
<p>{{cfg.address}}</p>
4
<p>{{cfg.age}}</p>
5
</ng-container>
6