简体   繁体   English

angular2 常规 onclick 不更新模型

[英]angular2 regular onclick doesn't update model

I have a div created in runtime with it's onclick bind to a function of the component.我在运行时创建了一个 div,它的onclick绑定到组件的函数。

let div = document.createElement("div");
div.onclick = this.divClick;
document.getElementById("container").appendChild(div);

The click function should update the model like this:点击函数应该像这样更新模型:

divClick(event) {
    this.divContent = event.target.innerHTML;
}

but the view is not updated with the divContent change.视图不会随着divContent变化而更新。 (when logging the value to console it's seems to be updated) (将值记录到控制台时,它似乎已更新)

When using the angular's (click) it works as expected.使用角度(click)它按预期工作。

<div (click)=divClick($event)>click me</div>

I believe the problem is related to the use of the regular onclick event, but I don't know how to solve this.我相信这个问题与使用常规的onclick事件有关,但我不知道如何解决这个问题。

You need to take care where this points to when divClick is called:divClick时,您需要注意this指向的位置:

Use one of:使用以下之一:

div.onclick = (e) => this.divClick(e);

or或者

div.onclick = this.divClick.bind(this);

IF you are creating div dynamically, you should bind event to that div dynamically.如果您正在动态创建 div,则应将事件动态绑定到该 div。 This answer may help you. 这个答案可能对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM