Hello World
Hello World

Reputation: 1129

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:

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

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. I can't find anything relevant on the official docs and ideally want to find a standardised way of doing this.

Upvotes: 2

Views: 1007

Answers (1)

JB Nizet
JB Nizet

Reputation: 692191

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.

The recommended way is to modify the model, and to use the template to generate HTML from the model:

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>

Upvotes: 5

Related Questions