0

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

1
  • You can use also the "safe operator" ?: <ng-container ...*ngFor="let column of person?.schoolInfo">, but to define an interface you need remove the ":", e.g. interface personInfo{schoolInfo:number[]} Commented May 31, 2022 at 19:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.