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?
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.
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.
OnChangeslinkA lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.
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; } }
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