简体   繁体   中英

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

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

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

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