Home > Enterprise >  Error when use ngFor to loop an array of object with no initialize data
Error when use ngFor to loop an array of object with no initialize data

Time:06-01

I'm using ngFor to loop through an array object but when the component start its has no data

person : personInfo[] = []

And this is the interface

 personInfo : {
           schoolInfo : {...}[]
           homeInfo : {...}[]
     }

and this is html code:

<ng-container [matColumDef]="colum.name"
 *ngFor="let column of person.shoolInfo"> //Property 'schoolInfo' does not exist on type personInfo
 <th>...</th>
 <td>...</td>
 </ng-container>

The person data will have when I trigger an button event but at the start person have no data to assign and I got the error like above

//Property 'schoolInfo' does not exist on type personInfo

What do I need to do to solve this problem? and thanks for your time

CodePudding user response:

Based on your usage for a person, the person must be an Object not an Array.

person: personInfo = {
  schoolInfo: []
  homeInfo: []
}

And then you can use it in ngFor without any problem.

CodePudding user response:

Another solution will be if you have multiple persons, you can generate multiple tables,

// person : personInfo[] = []; - this was written
persons : personInfo[] = []; // instead make it persons

In the HTML or template let's make the changes accordingly to make this code work.

<ng-container *ngFor="let person of persons">
  <ng-container [matColumDef]="colum.name" 
    *ngFor="let column of person.shoolInfo"> 
    //Property 'schoolInfo' does not exist on type personInfo

    <th>...</th>
    <td>...</td>
  </ng-container>
</ng-container>
  • Related