1

In my project I'm loading some elements dynamically.But I'm not able to generate click events for that elements.

import {Component, DynamicComponentLoader, Injector} from 'angular2/core';


@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <button (click)="form()">
    View Form
  </button>
    <div id="form" [innerHTML]="">
      Welcome..! Here form component will be loaded.

    </div>
  `,
  directives: []
})
export class App {
    private strForMarkets = "";
    private sbForMarkets: Array<string> = [];
  constructor(public dcl:DynamicComponentLoader, public _injector:Injector) {
  }
  form() {
      var s = ["a", "s", "d", "p"];
      this.sbForMarkets.push("<div><ul>")
      for (var index = 0; index < s.length; index++) {
          var element = s[index];
          this.sbForMarkets.push("<li class='OH liDataLeftFilterMarketsContainer'>");
          this.sbForMarkets.push("<div class='FL sprite_icon expand-icon-market'></div>");
          this.sbForMarkets.push("<div class='expand-text-div CP FT14 LH15' (click)='chill($event)' >" + element + "</div>");
          this.sbForMarkets.push("</li>");
      }
      this.sbForMarkets.push("</ul></div>");
      this.strForMarkets = this.sbForMarkets.join("");
  }

  chill() {
      console.log("Dude... Chill  ");
    }
}

p.s. I have tried with dynamic component loader but it works if all html in template only.

Lucifer
  • 1,069
  • 4
  • 16
  • 26
  • Where are you adding it? How does the `this.dcl.loadXxx()` code look like? `DynamicComponentLoader` is deprecated use `ViewContainerRef.createComponent()` instead. For an example see http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Jul 01 '16 at 08:02

1 Answers1

0

Angular2 doesn't process HTML added dynamically using [innerHTML]="..." or similar in any way (click) is just ignored and added as-is.

If possible wrap the HTML in a component and use ViewContainerRef.createComponent() instead. For an example see Angular 2 dynamic tabs with user-click chosen components

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks. And I have another doubt in that example you have separate components for the data you have. My data is coming from database. So I cannot have components right? – Lucifer Jul 01 '16 at 09:44
  • Do you mean content like `FT14 LH15`? You can use Angular binding to add it to the DOM like `{{someProp}}` or `*ngFor` to generate HTML from data. https://angular.io/docs/ts/latest/guide/template-syntax.html – Günter Zöchbauer Jul 01 '16 at 09:54
  • I don't know what FT14 and LH15 mean but that link can solve my problems. – Lucifer Jul 01 '16 at 09:59
  • The link shows how to add components dynamically but the HTML of the contents is static but supports binding like `[]` and {{}}`. – Günter Zöchbauer Jul 01 '16 at 10:01