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
  • 43,715
  • 16
  • 163
  • 170
naomi
  • 2,443
  • 2
  • 18
  • 38

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
  • 558,509
  • 191
  • 1,911
  • 1,506
0

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

Community
  • 1
  • 1