typescript Angular 2 监听模型变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35481871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:17:35  来源:igfitidea点击:

Angular 2 listen on model change

typescriptangular

提问by Denko Mancheski

How can I listen for changes on ngModel ? The problem: is that if i link (change) or (click) event to the element, in the given function when I access the model, its still not changed. If I add setTimeout of 500ms than I can the changed model. Any idea how can I get the real changed object without setTimeout which is very bad way ? Code in the html:

如何监听 ngModel 的变化?问题是:如果我将 (change) 或 (click) 事件链接到元素,在我访问模型时的给定函数中,它仍然没有改变。如果我添加 500 毫秒的 setTimeout,我可以更改模型。知道如何在没有 setTimeout 的情况下获得真正更改的对象,这是非常糟糕的方式吗?html中的代码:

<input type="checkbox" (click)="autoJoinToggle()" [(ngModel)]='active.bookmark.autoJoin'> Autojoin

Code in the component:

组件中的代码:

 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

I cannot do this with Angular Control because I need the model binded and the "active" object does not exist in first place, and if I want to update the value of the control after "active" is defined, I need to listen on changes on the "active" object (which changes overtime). The same problem is with local variable and @ViewChild -> I still need to know when "active" changes so I update the local variable too.

我无法使用 Angular Control 执行此操作,因为我需要绑定模型并且首先不存在“活动”对象,如果我想在定义“活动”后更新控件的值,我需要监听更改在“活动”对象上(随着时间的推移而改变)。局部变量和@ViewChild 也有同样的问题 -> 我仍然需要知道“活动”何时发生变化,所以我也更新了局部变量。

Here is a gif as well: enter image description here

这里还有一个 gif: 在此处输入图片说明

采纳答案by Günter Z?chbauer

(ngModelChange)="doSomething($event)"

or

或者

autoJoinToggle(cb){ this.active.bookmark.autoJoin = cb; //do something.. }

<input #cb type="checkbox" (click)="autoJoinToggle(cb.checked)" 
    [(ngModel)]='active.bookmark.autoJoin'>

I think the behavior you explain is a bug though and a pull request already provided but not added https://github.com/angular/angular/issues/6311.

我认为您解释的行为是一个错误,并且已经提供了拉取请求但未添加https://github.com/angular/angular/issues/6311