When should you use ngOnChanges? Use ngOnChanges whenever you want to detect changes from a variable decorated by @Input. Remember that only changes from the parent component will trigger this function. Also remember that changes from the parent still update the child value even without implementing ngOnChanges.
The ngOnChnages is a life cycle hook, which angular fires when it detects changes to data-bound input property. This method receives a SimpeChanges object, which contains the current and previous property values. There are several ways the parent component can communicate with the child component.
If you click on the “set to Parent” button multiple times, the child component setter won't be triggered from 2nd time onward. Thus it looks like the Input setter is only being fired once, if the value of setter hasn't been changed.
"ngOnChanges" is a lifecycle hook for an Angular component to know when the @Input props are changed. The main drawback of using ngOnChanges is that you have to write much more code to watch a single prop. Angular team also provides another way to intercept the property changes by setter.
One advantage of ngOnChanges()
is that you get all changes at once if your component has several @Input()
s.
If your code only depends on a single @Input()
a setter is probably the better approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With