2

I have an input variable called model for childComponent. @Input () model: any;

I have a parent control parentControl that send the updated input variable to childComponent.

How do I code childComponent to react to model changes? I want a childComponent call made when model changes.

Thoughts?

reza
  • 5,972
  • 15
  • 84
  • 126

1 Answers1

7

Consider using ngOnChanges() lifecycle

@Input() model: any;
ngOnChanges(model: any) {
    this.doSomething(model);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • 1
    and if there are multiple input parameters will I have one ngOnChanges for each input variable? – reza Aug 16 '17 at 17:10
  • yes you need to do that, there is no such watchgroup in angular2 like we have in angularjs – Sajeetharan Aug 16 '17 at 17:11
  • 1
    @reza no, you don't, the argument to the single `ngOnChanges` method is actually `SimpleChanges`, which contains the changes to *any* of the inputs. You can see this in the docs linked, not sure why the author is saying otherwise. – jonrsharpe Aug 16 '17 at 22:02
  • @reza yes, you are right! actually i was mentioning about using a set_method , in that case you need separate ones. but ngOnchanges usually give whatever the inputs if they are changed. sorry i have not read your comment properly. https://angular.io/api/core/OnChanges – Sajeetharan Aug 17 '17 at 01:35
  • This is close, but is not actually correct. I will give an example with a boolean data binding ``` @Input() yourData: boolean; ngOnChanges(changes: SimpleChanges) { console.log('changes: ', changes); // this will console out all of the changes it detected. console.log('changes.yourData: ', changes.yourData); // this will console out yourData old and yourData new. } ``` the changes.yourData would output like this in console. ``` changes.yourData: { currentValue: true, firstChange: false, previousValue: Undefined } ``` previousValue will update on second change – anothercoder Jun 23 '20 at 18:12