0

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.

LadyCode
  • 1
  • 2
  • Do you want to capture what user types ? – programoholic Feb 15 '19 at 07:47
  • Have you removed the readonly property and and checked whether the onChange() triggers or not? – Sivaramakrishnan Feb 15 '19 at 07:48
  • you are using `ngModelChange` also `ngModel` why two, Two-way bindings? – Pardeep Jain Feb 15 '19 at 07:48
  • Try to use (change) instead of (ngModelChange) – Sherly Febrianti Feb 15 '19 at 08:30
  • 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 Feb 15 '19 at 09:14
  • @WomenWhoCode Do you change the field1 value from another function? If you are using "readonly", it means you cannot type anything on the input. So, how come you are expecting the input can changed? need to know what you are trying to do. – Sherly Febrianti Feb 15 '19 at 18:29

3 Answers3

0

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

Here is some explanation to help you understand this.

Sherly Febrianti
  • 1,097
  • 15
  • 33
0

Use input like this:

(input)="handle($event)"

And Handle event in your typescript accordingly.

Aayush
  • 409
  • 4
  • 17
0

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 ;)

AT82
  • 71,416
  • 24
  • 140
  • 167