How to detect changes in a component when a user changes something in a view in Angular 2?

I am trying to detect changes if the user has changed the value for the type of input (for example, for a switch, text input, text input area, etc.).

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

I do not want to use (ngModelChange) = "detectChanges ($ event)" to detect the changes I need to make it general so that I can use for the entire input type of the component

+4
source share
1 answer
<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 the example.

mileage getter/setter, , , , .

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

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

. , . ngModel , , , .

+2

Source: https://habr.com/ru/post/1656903/


All Articles