Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In angular2, how to get onChanges for properties changed on an object sent in for an @Input

Tags:

angular

I have a directive and on it is an @Input that accepts a class.

@Directive({selector: 'my-directive'}) @View({directives: [CORE_DIRECTIVES]}) export class MyDirective  {     @Input() inputSettings : SettingsClass;     @Input() count : number;     onChanges(map) {       console.log('onChanges');     } } 

The directive is used in html:

  ...   <my-directive [input-settings]="settings" [count]="settings.count"></my-directive>   ... 

If the settings.count is changed then the onChanges will fire. If any other property on the settings class changes, then it will not fire.

How can I detect if there is a change to any property on settings?

like image 467
Peter Avatar asked Dec 07 '15 00:12

Peter


People also ask

How does angular 8 determine value change?

The answer is using observables. To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.

What triggers ngOnChanges?

ngOnChanges triggers following the modification of @Input bound class members. Data bound by the @Input() decorator come from an external source. When the external source alters that data in a detectable manner, it passes through the @Input property again.

What is the use of Onchange in angular?

OnChangeslinkA lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.


1 Answers

Angular will only notice if the object has been changed to a different object (i.e., the object reference changed), so ngOnChanges() can't be used to solve your problem. See Victor Savkin's blog post for more information.

You could implement the ngDoCheck() method in your MyDirective class. That lifecycle hook is called "every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check."

To implement your custom check method, you would first need to implement an .equals() method on class SettingsClass such that you could then write code something like the following in ngDoCheck():

ngDoCheck() {    if(!this.inputSettings.equals(this.previousInputSettings)) {       // inputSettings changed       // some logic here to react to the change       this.previousInputSettings = this.inputSettings;    } } 
like image 170
Mark Rajcok Avatar answered Oct 08 '22 21:10

Mark Rajcok