0

I have a component that display attributes of an object on form. I used getter/setter method of typescript to detect the changes of 2-ways data binding on form using model. Here's my code:

export class AlterInfoComponent implements OnInit {

  _alterInfos: any = {};
  @Output() alterInfosChanges = new EventEmitter();
 @Input() get alterInfos () {
    return this._alterInfos;
  };

  set alterInfos(val) {
    this._alterInfos = val;
    this.alterInfosChanges.emit(val);
    console.log('Alter Infos Changed: ', this._alterInfos);
  }
}

And my HTML template code:

<div>
    <input type="text" [(ngModel)] = "alterInfos.id">
    <input type="text" [(ngModel)] = "alterInfos.name">
</div>

When I change the input on html form, the console log doesn't return any message. Any suggest?

TheRemjx
  • 105
  • 1
  • 6
  • 1
    When you change input, it just changes one of the properties of alterInfos object, not the whole alterInfos object. Obviously, your setter for alterInfos is not getting called and hence no console message. You might need to write getter/setter for each of the properties of object to track the changes on each of the properties. – Alok Jha May 23 '17 at 04:02
  • @AlokJha Thank you for your quickly reply. With your answer I understood my problem. However, when my form has too much field, the Component class become bigger and bigger with just getter/ setter method. Have you got any suggest about this – TheRemjx May 23 '17 at 04:06
  • 1
    You need to use angular forms, preferably FormBuilder to detect changes in any of the input fields in your forms. For more information you can check answer https://stackoverflow.com/questions/34615425/how-to-watch-for-form-changes-in-angular-2 – Alok Jha May 23 '17 at 04:23
  • @AlokJha thanks for your great answer. I was underestimate FormBuilder until your answer – TheRemjx May 23 '17 at 04:40

0 Answers0