kamilkp
kamilkp

Reputation: 9800

Load dynamic component created on the fly in angular2 final

Previously with DynamicComponentLoader I was able to write like this:

import {Directive, Component, ViewContainerRef, DynamicComponentLoader} from '@angular/core';

@Directive({
  selector: '[some-directive]'
})
export class SomeDirective {
  costructor(dcl: DynamicComponentLoader, viewContainerRef: ViewContainerRef) {
    // fetch template from the server
    fetch(...).then((template) => {
      @Component({
        selector: 'div[some-relatively-unique-attribute-name]',
        template: template
      })
      class AdHocComponent {}

      dcl.loadNextToLocation(AdHocComponent, viewContainerRef).then(() => {
        console.log('success');
      });
    });
  }
}

Now with angular2 final and NgModules I see examples like this: http://plnkr.co/edit/P0spNzu8JbQad2aKACsX?p=info

(Discussed here https://github.com/angular/angular/issues/10735)

To dynamically load a HelloComponent but it requires the HelloComponent to be declared up front when the root NgModule is being created.

How can I load an ad-hoc created component into my view?

I found this: http://plnkr.co/edit/wh4VJG?p=preview But it is an insane amount of code to achieve a simple task like that.

Upvotes: 2

Views: 730

Answers (1)

yurzui
yurzui

Reputation: 214335

This might be that what you're looking for:

export class App {
   @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;

  constructor(private compiler: Compiler) {}

  addItem () {
     @NgModule({declarations: [HelloComponent]})
    class DynamicModule {}

    this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
      .then(({moduleFactory, componentFactories}) => {
        const compFactory = componentFactories
           .find(x => x.componentType === HelloComponent);
        const cmpRef = this.viewContainerRef.createComponent(compFactory, 0);
      });
  }
}

See also live Plunker

Related question:

Upvotes: 2

Related Questions