如何在ngModel上监听更改? 问题是:如果我将链接(更改)或(单击)事件链接到元素,则在访问模型时给定的函数中,它仍未更改。如果我添加500ms的setTimeout比我可以更改的模型。任何想法如何在没有setTimeout的情况下获得真正改变的对象,这是非常糟糕的方式? html中的代码:
<input type="checkbox" (click)="autoJoinToggle()" [(ngModel)]='active.bookmark.autoJoin'> Autojoin
组件中的代码:
console.log(this.active.bookmark.autoJoin) // returns the current value (before the change)
setTimeout(() => {console.log(this.active.bookmark.autoJoin);}, 500); //returns the value after the change
我无法使用Angular Control执行此操作,因为我需要绑定模型并且“活动”对象不存在于首位,如果我想在定义“active”之后更新控件的值,我需要听取“活跃”对象的变化(随时间变化)。同样的问题是局部变量和@ViewChild - &gt;我仍然需要知道何时“活动”更改,所以我也更新了本地变量。
答案 0 :(得分:10)
(ngModelChange)="doSomething($event)"
或
autoJoinToggle(cb){ this.active.bookmark.autoJoin = cb; //do something.. }
<input #cb type="checkbox" (click)="autoJoinToggle(cb.checked)"
[(ngModel)]='active.bookmark.autoJoin'>
我认为您解释的行为是一个错误,并且已经提供了拉取请求但未添加https://github.com/angular/angular/issues/6311。