0

I am using a div with an ngIf like following:

<div class="..." *ngIf="list; else loading">
   ....
</div>

<ng-template #loading>
   ....
</ng-template>

everything is working fine. The list is updated in the component after my service returns with data.. The only problem is, the DOM is only being updated, after the user clicks or scrolls. Otherwise the Loading Template is staying...

Im using the same construct in other parts of my project. It's working fine there.. Anybody knows why this is happening and how to resolve this?

Update:

At first i was using the ngIf with an async pipe

<div class="..." *ngIf="listObs | asnyc; else loading">
   ....
</div>

Right now im subscribing manually in the component

this.subscriptions.add(this.dataService.listObs.subscribe((list: Array<any>) => {
       this.list = list;
}

Both ways end in the same result. DOM is only being updated after user interaction. Adding this.changeDetectorRef.detectChanges(); in the manual subscription "solves" the problem.

Kai
  • 1
  • 1
  • what is a list, a boolean? – Ramesh Reddy Dec 02 '19 at 09:16
  • Can you try to inject ChangeDetectionRef in the constructor and use this.changeDetectionRef.detectChanges after you assign the data? – Jacopo Sciampi Dec 02 '19 at 09:17
  • @Ramesh an array of objects – Kai Dec 02 '19 at 09:30
  • @JacopoSciampi call detectChanges "fixes" the problem. But why is it working without calling detectChanges at other parts of my project? – Kai Dec 02 '19 at 09:31
  • 1
    detectChanges forces the DOM to be rendered with the new data. Is usually used when the component use the OnPush strategy. Are you using it? You can see it in your component's decorator. – Jacopo Sciampi Dec 02 '19 at 09:36
  • no im not using it. thats why i'm confused. – Kai Dec 02 '19 at 09:37
  • That's confusing me aswell. Can you add to your question the part where you get and assign the data? – Jacopo Sciampi Dec 02 '19 at 09:39
  • @Kai make sure the list is a falsy value until the array is assigned to it. – Ramesh Reddy Dec 02 '19 at 09:58
  • i guess the problem is the array. on change, the old array and the new array are compared. not for its values but for its references i guess. – Kai Dec 02 '19 at 10:09
  • According to https://stackoverflow.com/questions/50519200/angular-6-view-is-not-updated-after-changing-a-variable-within-subscribe maybe the problem is the array update not triggering the DOM update. That's why the detectChanges works. Also, I believe the if you wrap your subscription into an this.ngZone.runoutsideangular function it will work aswell. But right now I don't have a clear answer to that. – Jacopo Sciampi Dec 02 '19 at 10:11
  • is there any performance reason to run it in ngZone? I can live with calling detectChanges. Just knowing why it doesn't work like i expected it to do, is a relieve. Thank you for your support! – Kai Dec 02 '19 at 10:18

0 Answers0