I'm trying to wrap my head around best practice when using Observables alongside ChangeDetectionStrategy.OnPush
.
The example demonstrates the common scenario of wanting to show some kind of loading message (or a simple spinner animation perhaps):
@Component({
selector: 'my-app',
template: `Are we loading?: {{loadingMessage}}`,
// Obviously "Default" will notice the change in `loadingMessage`...
// changeDetection: ChangeDetectionStrategy.Default
// But what is best practice when using OnPush?
changeDetection: ChangeDetectionStrategy.OnPush
})
export class App implements OnInit {
private loadingMessage = "Wait for it...";
constructor() {
}
ngOnInit() {
// Pretend we're loading data from a service.
// This component is only interested in the call's success
Observable.of(true)
.delay(2000)
.subscribe(success => {
if(success){
console.log('Pretend loading: success!');
// OnPush won't detect this change
this.loadingMessage = 'Success!';
}
});
}
}
I more or less understand the requirement for immutability with OnPush
and, to me at least, it currently makes sense when talking about actual model data (likely held in some kind of store).
So, I have two questions:
- Why doesn't the assignment of the new string value
'Success!'
trigger the change detector? As far as immutability is concerned, the value has changed, right? - How should lightweight internal component state (ie.
loadingMessage
) be implemented when usingChangeDetectionStrategy.OnPush
? If there are multiple best practices, please point me in the right direction.