Following are my undestanding on onPush change detection strategy. OnPush change detection is triggered if one of the following happens
- A bound event is received on the component.
- An input was updated.
Async
pipe received an event.- Change detection was invoked manually.
From the above list, An input was updated
has to be reference change, so the input has to immutable.
This is my scenario.
I have parent component Parent
where I subscribe to an observable to fetch data from an API call and I pass this data to the child component via @Input
.
Parent Component
@Component({
template: '<child-component [data]="data"></child-component>'
})
export class ParentComponent implements OnInit {
this.dataService.get().subscribe(data => {this.data = data})
}
Child Component
@Component({
selector: 'child-component',
template: '{{data.name}}',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() data;
constructor() {
console.log(this.data)
// undefined, because the data is async response and not available while bootstrapping.
}
ngAfterContentChecked() {
console.log(this.data) // available
}
}
The problem here is if we add onPush
change detection strategy to the child component and the input reference is not changed, the changes are not propagated from parent to child. The reason is because onPush
strategy expects the inputs to be immutable. How to overcome this situation?
Any help is greatly appreciated.
Update
On googling I found this blog post by Victor Savkin
If a component depends only on its input properties, and they are observable, then this component can change if and only if one of its input properties emits an event.
So can we pass observables
to the inputs and fix this? If so please propose a working solution.
Please note that I don't want to use asyn
pipe in template or manually trigger change detection.