Search code examples
htmlangularangular-ng-if

Angular ngIf problem - html not rendered - data exist


I am having an issue with data displayed on my page after retrieving it from the API.

API is returning array of objects so I am having multiple *ngIf's in order to know what html div to show. Its important to say that API is not returning all objects every time, it depends on the data.

The thing is that after first call of an API, html is rendered properly and everything is displayed as it should. On second call (input parameters are of course different now), API is returning different data (more objects), but HTML is the same, so I am missing a several div's on the page. If I refresh the page and call the API again, I am getting the well rendered html.

console.log(this.data) is always displaying correct informations.

I tried using this.changeDetector.detectChanges() and this.ngZone.run solutions found here on SO, but that didnt solved my issue.

Is there anything else I can try?

This is my code example:

this.repoService.getData(а, b)
 .subscribe(res => {
   this.data = res as ApiData;
})

and I have several if's like this, for each object

if (this.data.objectA === undefined || this.data.objectA.length === 0) {
            this.objectAExist = false;
}
export interface ApiData {
    objectA: aData[];
    objectB: bData[];
    objectC: cData[];
    objectD: dData[];

I also have several div's like this with ngIf and ngFor.

<div *ngIf="objectAExist">
    <div *ngFor="let item of data.objectA">
      <div>
         <p>Label 1</p>
         <p>Label 2</p>
         <p>Label 3</p>
      </div>
    <div>
         <p>{{ item.Id }}</p>
         <p>{{ item.Name }}</p>
         <p>{{ item.Description }}</p>
         </div>
   </div>
</div>

Solution

  • I have managed to solve this issue by moving the logic to html part.

    I replaced this

    <div *ngIf="objectAExist">
    

    with this

    <div *ngIf="data.objectA.length > 0">
    

    and everything works as expected.