Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...