简体   繁体   English

动态将Angular2组件添加到dom

[英]Dynamically append Angular2 components to the dom

I want to be able to click a button in order to add a new component. 我希望能够单击一个按钮以添加新组件。 So for example, if Angular 2 was more like Angular 1 I could do: 因此,例如,如果Angular 2更像Angular 1,我可以这样做:

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

ts: TS:

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

note: I know similar questions have been asked a few times on here but the answers I have read have been contradictory and mostly reliant upon deprecated code such as DynamicComponentLoader. 注意:我知道类似的问题已经在这里问过几次,但我读到的答案是矛盾的,并且大多依赖于不赞成使用的代码,例如DynamicComponentLoader。 I can't find anything relevant on the official docs and ideally want to find a standardised way of doing this. 我在官方文档中找不到任何相关内容,并且理想情况下是希望找到一种标准化的方式来执行此操作。

No. Angular 2 is pretty much as Angular 1, and doing that in Angular 1 has never been the recommended way of manipulating the DOM. 不会。Angular2与Angular 1差不多,在Angular 1中这样做从来不是推荐的操作DOM的方法。

The recommended way is to modify the model, and to use the template to generate HTML from the model: 推荐的方法是修改模型,并使用模板从模型生成HTML:

private components = [];

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

and in the template: 并在模板中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM