I want to bind a click-event to dynamically generated HTML in Angular Dart. How to do it correctly?

What I have tried:

home_component.dart:

void addHtml() {
 html = """
  <div class="offer" (click)="offerGo()">
   ....
  </div>""";

  offers.setInnerHtml(html);
}

void offerGo() {
 print("Offer clicked!");
}

The HTML is correctly added however I get the following warning in the browser console:

Removing disallowed attribute <DIV (click)="offerGo()">

... and the click event does not fire when an offer is clicked.

1

There are 1 answers

2
Günter Zöchbauer On BEST ANSWER

There is no way to make property or event bindings or component- or directives being instantiated for dynamic added HTML.

Angular doesn't process HTML added dynamically in any way.

Removing disallowed attribute

Is not directly related to Angular, but rather plain dart:html. See also Removing disallowed attribute

You can only add event handlers imperatively to HTML added dynamically:

void addHtml() {
 html = """
  <div class="offer">
   ....
  </div>""";

  offers.setInnerHtml(html);
  offers.querySelector('div.offer').onClick.listen(offerGo);
}

void offerGo() {
 print("Offer clicked!");
}