1

I have a div created in runtime with it's onclick bind to a function of the component.

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. (when logging the value to console it's seems to be updated)

When using the angular's (click) it works as expected.

<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.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
naomi
  • 2,583
  • 2
  • 22
  • 39

2 Answers2

1

You need to take care where this points to when divClick is called:

Use one of:

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

or

div.onclick = this.divClick.bind(this);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

IF you are creating div dynamically, you should bind event to that div dynamically. This answer may help you.

Community
  • 1
  • 1