2016-07-01 44 views
0

在我的項目中,我正在動態加載一些元素。但我無法爲這些元素生成單擊事件。動態組件單擊事件綁定Angular2

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.我已經嘗試過使用動態組件加載器,但只有在模板中的所有HTML都可以使用。

+0

你在哪裏添加它? 'this.dcl.loadXxx()'代碼是怎麼樣的?改爲使用'ViewContainerRef.createComponent()'代替'DynamicComponentLoader'。有關示例,請參閱http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 –

回答

0

Angular2不會處理使用[innerHTML]="..."或其他類似方式動態添加的HTML (click)只是被忽略並按原樣添加。

如果可能,請將HTML包裝到組件中,並改爲使用ViewContainerRef.createComponent()。舉例見Angular 2 dynamic tabs with user-click chosen components

+0

謝謝。在這個例子中我還有另外一個疑問,那就是你有獨立的數據組件。我的數據來自數據庫。所以我不能擁有正確的組件? – Lucifer

+0

你的意思是像「FT14 LH15」這樣的內容嗎?您可以使用Angular綁定將它添加到DOM,如'{{someProp}}或'* ngFor'來從數據生成HTML。 https://angular.io/docs/ts/latest/guide/template-syntax.html –

+0

我不知道FT14和LH15是什麼意思,但是這個鏈接可以解決我的問題。 – Lucifer