1

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.

Blackbam
  • 17,496
  • 26
  • 97
  • 150

1 Answers1

1

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!");
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • The answer does not make me happy but thanks. It may be another question but in jQuery you could do `$(document).on('click','.offer',function(e) { alert(e.target); })` which applies to dynamic HTML also. Do you know some similar possibility to define event listeners to listen globally like this in angular? – Blackbam Mar 01 '17 at 16:43
  • 1
    An alternative approach is to create components dynamically at runtime (and I mean create dynamically, not only add dynamically) like shown in http://stackoverflow.com/questions/34784778/equivalent-of-compile-in-angular-2/37044960#37044960 but this way you loose AoT capability. – Günter Zöchbauer Mar 01 '17 at 16:51