Reputation: 237
Ok, so I faced an issue and can't find a solution
Please read carefully
I want to check in my angular template for a property and then to attach style to it.
The problem: it only works for the first child property.
For example I want to apply some style to my div, so I check this:
[ngStyle]="{'flex-flow': data.section.a.subtitle ? 'column' : 'row' }"
Angular can only check for the first path data.section
And I know that because I tried a nested *ngIf
in other cases, for example if the JSON structure is
"batters":
{
"batters":
{ "id": "1001", "type": "Regular" }
}
and I want to check the 'id' property in angular, I need to do something like:
<ng-container *ngIf="batters">
<ng-container *ngIf="batters.batters">
<ng-container *ngIf="batters.batters.id">
{{ batters.batters.id }}
</ng-container>
</ng-container>
</ng-container>
If I'm trying to go straight to the prop like: <ng-container *ngIf="batters.batters.id">
I got this:
ERROR TypeError: Cannot read property 'id' of undefined
So in this case I can nest the *ngIf
's but what can I do for the example above?
Is there a better way to check for a nested prop in Angular?
Upvotes: 3
Views: 595
Reputation: 24424
Normaly this error happen when the json data going to be requested from api so if you don't initialize the property of an object you will end up try to do this way undefined.proprty
.
safe navigation operator will check the property value not undefined and the try to access to next proprty
<ng-container *ngIf="batters?.batters?.id">...</ng-container>
you need to use ?. operator always if the property gone to be initialized later by any async operation http , setTimeout ..
Upvotes: 1
Reputation: 2128
Yeah you can bind in a single if condition like this by using &
operator
<ng-container *ngIf="batters && batters.batters && batters.batters.id">
{{ batters.batters.id }}
</ng-container>
I think this is what you expect - hope it helps happy coding !!
Upvotes: 3
Reputation: 3297
You can work with save Navigation operator ?
to avoid this kind of errors :
{{ batters?.batters?.id }}
Regards,
Upvotes: 2