angular - know when template rendering is finished - with async pipe

Viewed 624

I am trying to implement a progress guage component to show the loading process of the template components which are rendered with async pipe.

Question is how do I know the rendering (with async pipe) is finished for a given component.

2 Answers

Use forkJoin rxjs operator to wrap your observable sources together. You'll get the response when the last value is received :

forkObservable$ = forkJoin({
    obs1: this.observable1$,
    obs2: this.observable2$,
    obs3: this.observable3$,
  });

This way you can display your gauge until the last emitted value is received (gauge being a simple value displayed for the example :

<ng-container *ngIf="forkObservable$ | async as forkObservable; else loading">
 <app-comp1>{{forkObservable.obs1}}</app-comp1>
 <app-comp2>{{forkObservable.obs2}}</app-comp2>
 <app-comp3>{{forkObservable.obs3}}</app-comp3>
</ng-container>

<ng-template #loading>
  loading {{dataLoaded}} / 3
</ng-template>

To update the value of the gauge (or 'dataLoaded' for the example), you can use the tap rxjs operator on each observable in order to update its value :

observable1$ = of('CyberTruck').pipe(
    tap(() => this.dataLoaded++)
  );

Here is a working example with Stackblitz using a delay on each observable in order to simulate the asynchronous behavior.

I assume you need loading progress before data rendered. *ngIf="obs$ | async as obs; else loading"

Related