[英]Dynamically append Angular2 components to the dom
我希望能夠單擊一個按鈕以添加新組件。 因此,例如,如果Angular 2更像Angular 1,我可以這樣做:
<button (click)="addComponent()">add</button>
TS:
addComponent():void {
let component = $compile('<component-selector></component-selector>')(scope)
ele.append(component)
}
注意:我知道類似的問題已經在這里問過幾次,但我讀到的答案是矛盾的,並且大多依賴於不贊成使用的代碼,例如DynamicComponentLoader。 我在官方文檔中找不到任何相關內容,並且理想情況下是希望找到一種標准化的方式來執行此操作。
不會。Angular2與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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.