I want to do that if my array doesn't have some values or some values are undefined in html just don't try to get it from array.
Empty array : [ {0: undefined} ]
Full array :
[
{0: "Name"},
{1: "img.src"},
{2: name: string, family: string, age: number}
]
0: "Name" , 1: "img.src" 2 {name: string, family: string; age: number}
My try which isn't working :
<div *ngFor="let fam of familyArray" class="grid-item">
<button ion-button>
<img *ngIf="fam[1] != undefined && fam[1] != null " class="selectImg" src="{{fam[1]}}" alt="">
</button>
<span *ngIf="fam[2].name != undefined && family[2].age != undefined && family[2].age != null && family[2].name != null " class="image-text">{{fam[2].name}}, {{family[2].age}}m.</span>
<p *ngIf="fam[2].family != undefined && fam[2].family != null " class="family-status">{{fam[2].family}}</p>
</div>
I always get this errors :
TypeError: Cannot read property '1' of undefined
or
TypeError: Cannot read property 'name' of undefined
You don't need to put checks for undefined and null, It take cares it self for undefined and nulls, you just need to specify like below:
<div *ngFor="let fam of familyArray" class="grid-item" >
<button *ngIf="fam[0]" ion-button>
<img *ngIf="fam[1]" class="selectImg" src="{{fam[1]}}" alt="">
</button>
<span *ngIf="fam[2] && fam[2].name && family[2].age" class="image-text">{{fam[2].name}}, {{family[2].age}}m.</span>
<p *ngIf="fam[2].family" class="family-status">{{fam[2].family}}</p>
</div>
The array of object which you are receiving is actually a wrong format, all the object should be in same types and some standard conventions need to be followed though.
<div *ngFor="let fam of familyArray" class="grid-item">
<button ion-button>
<img *ngIf="fam['1'] != undefined && fam['1'] != null " class="selectImg" src="{{fam['1']}}" alt="">
</button>
<span *ngIf="fam['2'].name != undefined && family['2'].age != undefined && family['2'].age != null && family['2'].name != null " class="image-text">{{fam['2'].name}}, {{family['2'].age}}m.</span>
<p *ngIf="fam['2'].family != undefined && fam['2'].family != null " class="family-status">{{fam['2'].family}}</p>
</div>
Above code 3 times as there are 3 objects in your array.
First time value of fam is {0: Name},
Second time {1: img.src},
and third time {2: name: Example, family: example, age:15}
there is not such object fam[1] I hope I have explained enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With