简体   繁体   中英

Angular 4 Readonly input change detection

I have following code with readonly input. am trying to change the value if this readonly input from TS File, but, I am unable to detect change from any function. Below is the example.

<input type="text" class="form-control" id="field1" name="field1" readonly [(ngModel)]="field1" (ngModelChange)="onChange()">

ngModelChange is not working in this senario.

You can try to use the (change) instead of (ngModelChange) .

Here is some explanation to help you understand this.

Use input like this:

(input)="handle($event)"

And Handle event in your typescript accordingly.

FormControl to the rescue!!

FormControls and Reactive forms are great and it will save your day! :)

Mark ReactiveFormsModule in your app.module, import FormControl to your component aaand... For demo I used a simple timeout to change the value to trigger the valueChanges :

myControl = new FormControl('')

constructor() { }

ngOnInit() {
  setTimeout(() => {
    this.myControl.setValue('something');
  }, 2000);

  this.myControl.valueChanges.subscribe((data) => {
    console.log('changed!')
  });
}

And template:

<input type="text" readonly [formControl]="myControl">

StackBlitz

PS if this is input is part of a template driven form, this wouldn't work, since ngModel and formControl shouldn't be used together. So you would be notified of that. So in that case I suggest you go reactive way ;)

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