0
votes

I have this components structure in app.component.html:

  <sidebar-container></sidebar-container>
  <router-outlet></router-outlet>

Sidebar container is a component that belongs to another module (sidebar.module). In the ngOnInit of the sidebarContainer component I have a property called "list" that's initiated as an empty array.

export class SidebarContainer implements OnInit {

  list: Array<any> = [];
  
  constructor(
   private http: HttpClient,
  ) {}

  ngOnInit():void {
  this.http.get('url').subscribe(
   res => this.list = res
  }

The list has this structure:

 [{id: 1, name: "Michael"}]

In Sidebar container component child I have only this template (sidebar is a component that has only a div for rendering the list passed as input):

<sidebar [list]="list"></sidebar>

Template of sidebar-component:

<div *ngFor="let l of list">{{l.id}}</div>

Now, when I launch the app and I try to debug data are not updated and I don't see anything. Http request starts when component is just loaded and ngfor seems not work. But when I initialized in the sidebar-component template a value of the array like this:

test -> {{list[0].id}}
<div *ngFor="let l of list">{{l.id}}</div>

I can see both of values.

I can't understand this situation. What am I doing wrong?

1
are there any errors in the browser console?Jason White
only when i try to see element in this way {{list[0].id}} Cannot read property 'id' of undefined. Component is loaded before http request is completedAndrew88
component is loaded before http request is completed...and for the first time property 'id' is undefined....Andrew88
You could try to change the changeDetection to onPush in the child componentMarek W
The changeDetection is just to onPush in the sidebar-container-component and in the sidebar-component...Andrew88

1 Answers

0
votes

In your template, put check condition if id is defined or not.

<div *ngFor="let l of list">{{l.hasOwnProperty('id')?l.id:''}}</div>