2

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.

Hello World
  • 1,102
  • 2
  • 15
  • 33
  • 1
    Possible duplicate of [Angular 2 dynamic tabs with user-click chosen components](http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components) – eko Nov 11 '16 at 13:21

1 Answers1

5

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>
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255