It works! the value displayed changes when the function return value change." /> It works! the value displayed changes when the function return value change." /> It works! the value displayed changes when the function return value change."/>

Angular - Detect <input /> value change with one way binding

3k Views Asked by At

I have this

<input [value]="SomeModel.ValueFunct()" readonly="readonly"/>

It works! the value displayed changes when the function return value change.

How can i detect if the value change?

UPDATE:

Using:

ngOnChanges(changes: SimpleChanges) : void{

or

(gModelChange)="function($event)"

or

(change)="function($event)"

with

[ngModel]="SomeModel.ValueFunct()"

doesn't work when the function change, only if user change the input (but in this case is readonly)

Plunk:

http://next.plnkr.co/edit/Rj3NjtcGXTo9upt9?open=lib%2Fapp.ts&deferRun=1&preview .

.

Same unsolved question:

ngModel changes, ngModelChange is not called

1

There are 1 best solutions below

5
Neeraj Shende On

So, instead of binding function directly, bind the actual value in the input tag. And in your typescript file, write the ngOnChanges() lifecycle event and detect this change.

So, if you want one-way data binding, then

<input [ngModel]="variable">

In your .ts file, import the OnChanges and SimpleChanges from angular/core

ngOnChanges(changes: SimpleChanges) {
        if(changes[variable]) {
          // Perform your actions.
        }
    }

If you want to work with the data changed in input field in html while working with one way data binding, you have to use (ngModelChange) as below :

<input [ngModel]="variable"(ngModelChange)="function_to_fire_on_model_change($event)">