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.

1

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.