Skip to content Skip to sidebar Skip to footer

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 render

Solution 1:

  • Angular renders the dom interanlly to generate actual DOM, and binds them using Zone.js, which is only one-way, changes made to DOM are not detected.

  • Angular only detects a change if it's ran inside Zone.js's scope.

  • Then there are other interanl bindings and generation procedures to make a component actually work and bind with rest of the app.

  • To Achieve what you're trying do, you'll have to use DynamicComponetLoader as @echonax mentioned, but since it's deprecated now, you should use ViewContainerRef.createComponent() instead.

For implementaion see THIS Answer or @Gunter's PLUNKER (hope he doesn't mind.)

Solution 2:

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)

addCmp(){
    console.log('adding');
    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.

Post a Comment for "Adding New Component Element To Dom In Angular 2 At Runtime Doesn't Render The Component"