Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular "ngif" doesn't work while getting a undefined value

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

like image 429
Angulandy2 Avatar asked Jan 02 '23 18:01

Angulandy2


2 Answers

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.

like image 103
VizardCrawler Avatar answered Jan 16 '23 03:01

VizardCrawler


   <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.

like image 21
Narendra Avatar answered Jan 16 '23 05:01

Narendra