2016-11-11 71 views
2

我希望能夠單擊按鈕以添加新組件。因此,舉例來說,如果角2更像角1我可以這樣做:將Angular2組件動態添加到dom中

<button (click)="addComponent()">add</button> 

TS:

addComponent():void { 
    let component = $compile('<component-selector></component-selector>')(scope) 
    ele.append(component) 
} 

注:我知道類似的問題已經被問過這裏幾次,但問題的答案我已經閱讀了矛盾,主要依賴於不推薦的代碼,如DynamicComponentLoader。我找不到與官方文檔相關的任何內容,並且希望找到一個標準化的方法來完成此操作。

+1

[角2動態的可能的複製用戶點擊選擇的組件標籤](http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components) – echonax

回答

5

編號Angular 2與Angular 1差不多,在Angular 1中這樣做並不是推薦的操作DOM的方式。

推薦的方法是修改模型,並使用該模板從模型中生成HTML:

private components = []; 

addComponent() { 
    this.components.push({}); // this object would typically contain the inputs of the component 
} 

,並在模板:

<component-selector *ngFor="let c of components"></component-selector>