Tek Tek - 2 months ago 21
Javascript Question

Adding new Component element to DOM in Angular 2 at runtime doesn't render the component

I'm trying to add dynamically (at runtime) new nodes in the DOM. The new nodes basically are the Component selectors. The problem is that the content of the component is not rendered so the result is just having empty HTML tags.

I'm using Angular 2.0 Documentation example and modified it a little bit just to show case.

Here is the plunker

All I do is to reuse the code and when I click on the body to create new sales-tax elements. Obviously it's not working.

This is the new script element I added ontop of body.

function add(){
var element = document.createElement('sales-tax');

and the function is invoked once I click the body.

<body onclick="add()">

This is the result. As you can see the sales-tax that has been added to the template pre runtime it's rendered but the ones that I add at runtime are empty.

This is the result


createComponent() version: Plunker

this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.theBody.createComponent(factory)

beta.17 (deprecated) version with .loadNextToLocation(): Plunker(deprecated)

    this.dcl.loadNextToLocation(HeroListComponent, this.theBody);

You are not creating a component you are just creating an html element and appending it to the DOM which happens to have the same name with a components selector.

In order to achieve what you want you have to use DynamicComponentLoader.