Search code examples
angularrxjsangular-template

angular rxjs observable inside ngIf-block miss first update


I have two observables. First observable is used for ngIf-Block Statement. Second observable is used inside the ngIf-Block and maps values from first observable.

The second observable do not get the first update from source inside the ngIf-Block. On otherhand, outside of ngIf-Block it works.

Any explanations for this unexpected behavior?

Example: https://stackblitz.com/edit/angular-rxjs-template-update-problem


Solution

  • This is happening because number$ is Subject and it's used inside *ngIf which means it subscribes to sum$ only after this template block is created and that happens after sum$ is updated with this.number$.next(1).

    So what you can do is using ReplaySubject(1) instead that will replay its latest item to every new subscriber so when the template async pipe inside *ngIf subscribes to it it gets the last value replayd and updates as you expect.

    Your updated demo: https://stackblitz.com/edit/angular-rxjs-template-update-problem-xb5f3s?file=src/app/app.component.ts