简体   繁体   中英

How to detect changes in Component when user has changed something on the view in Angular 2?

I am trying to detect the changes when suppose user has changed value for input type(like for radio button,input text,input text area etc.)

<input type="text" pInputText [(ngModel)]="mileage"/>

I don't want to use (ngModelChange)="detectChanges($event)" to detect the changes coz i need to make it generic so that i can use for whole component's input type

<form #myForm>
  <input type="text" pInputText [(ngModel)]="mileage" name="xxx"/>
  ...
</form>
class MyFormComponent {
  @ViewChild('myForm') myForm:NgForm;

  ngAfterViewInit() {
    this.myForm.valueChanges.subscribe(val => console.log(val));
  }
}

https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#template2 also uses this method in an example.

You could also make mileage a getter/setter, then you can put code into the setter that is executed when the value changed, but that needs to be done for each property an input is bound to.

You can also add

@HostListener('change', ['$event'])
onChange(e) {
  console.log(e);
}

@HostListener('input', ['$event'])
onInput(e) {
  console.log(e);
}

You need to add a listener for every event you might be interested. There are some differences between browser what events they fire for what edit action. ngModel abstracts some differences away which you might need to take care of yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM