When to use ngOnChange, SimpleChange, Setters and changeDetectorRef in Angular
Why ngOnChange?
If you are working in a large enterprise application, we have to create small components. Small components are much more flexible in terms of reusability and maintainability. When you create small components, child, or compound components, you have to pass data every time refreshed from an API. ngOnChange life cycle hook helps in updating data before ngOnInit called.
ngOnChanges respond when data-bound input properties changes. The method receives a SimpleChanges object of current and previous property values. ngOnChanges methods come in OnChanges interface. SimpleChange
is a class that implements current and previous values. In the below code we are defining inputValue
that is coming from the parent component.
@Input() inputValue: string; ngOnChanges(changes: SimpleChanges) { console.log(changes.inputValue.currentValue);console.log(changes.inputValue.previousValue);
}
Similarly we can define ngOnChanges with any input. This can be used when we are using two-way data binding.
@Input() inputValue: string; ngOnChanges() { //Set all…