component.ts
export class MyComponent implements OnInit {
constructor(
private router: Router,
private store: Store<fromApp.State>
) {}
loading: boolean;
ngOnInit(): void {
this.store.select('myState').subscribe(({ loading }) => {
this.loading = loading;
console.log(this.loading);
});
}
}
component.html
<div *ngIf="loading">
loading
</div>
<div *ngIf="!loading">not loading</div>
In the browser console i can see the switch between the two states loading=false and loading=true. However, in the browser i always see "loading". What am i missing here?
CodePudding user response:
It means the change detection cycle is not triggered when your observable is firing. It typically arises when OnPush strategy is used (-> improves performance because less detection cycles run, but you have to be more explicit about changes in counterpart).
So there are 3 ways to fix your issue:
- Disable OnPush strategies in your component tree (wouldn't recommend, you certainly benefit from it elsewhere)
- You explicitly run change detection cycle:
constructor(..., private cdr: ChangeDetectorRef) {...}
// then in your subscription code:
this.loading = false;
this.cdr.markForCheck();
- You use async pipe in your component template code, because it plays nicely with
ngZone:*ngIf="loading$ | async", which means your loading observable is left as is:loading$ = this.store.select('myState').pipe(map(s => s.loading)).
