Angular 2 Dart: How to bind events correctly to dynamically generated HTML (Removing disallowed attribute <DIV (click)="…">)?

Issue

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.

Solution

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!");
}

Answered By – Günter Zöchbauer

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *