0
votes

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.

3
Do you want to capture what user types ? - programoholic
Have you removed the readonly property and and checked whether the onChange() triggers or not? - Sivaramakrishnan
you are using ngModelChange also ngModel why two, Two-way bindings? - Pardeep Jain
Try to use (change) instead of (ngModelChange) - Sherly Febrianti
I want to perform certain functionality based on value change. I tried to remove readonly, in that case if user enters value in that particular field, it works. But my requirement is to catch the value changed by TS file in readonly input and perform functionality. I hope it is clear. - LadyCode

3 Answers

0
votes

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

Here is some explanation to help you understand this.

0
votes

Use input like this:

(input)="handle($event)"

And Handle event in your typescript accordingly.

0
votes

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

P.S 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 ;)