I have a straightforward component that contains a BehaviorSubject
. Within my template, I utilize the async
pipe to display the most recent value from the BehaviorSubject
.
When the value is emitted during the OnInit
lifecycle hook, the view updates correctly with the new value. However, when I emit a value during the AfterViewInit
hook, the async
pipe does not update the view.
Is this behavior expected? Why does the async
pipe fail to update the second emitted value?
Below is an example of the component code:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements OnInit, AfterViewInit {
public test$ = new BehaviorSubject(0);
constructor(public cd: ChangeDetectorRef) {
// All three values are logged - 0, 100, 200
this.test$.subscribe(console.log);
}
ngOnInit() {
// View is updated with value 100
this.test$.next(100);
}
ngAfterViewInit() {
// View is not updated, async pipe is not triggered
this.test$.next(200);
}
}
And here's an example of the component template:
<h1>{{ test$ | async }}</h1>