Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 setters vs ngOnChanges

People also ask

Is it OK to use ngOnChanges in Angular?

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.

What is ngOnChanges in Angular?

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.

Why Angular input setter is only being fired once?

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.

Is ngOnChanges required?

"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.