2

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.

kamilkp
  • 9,690
  • 6
  • 37
  • 56
  • 1
    *Here: [How can I use/create dynamic template to compile dynamic Component with Angular 2.0?](http://stackoverflow.com/q/38888008/1679310) is how to use RuntimeCompiler and produce dynamic templates and components on the fly* – Radim Köhler Sep 16 '16 at 14:47
  • I saw it, this is the question from which I took the link to the "working" plunker. But this is an insane amount of code to achieve sth that was achievable in a couple of lines of code in previous version of angular2. Isn't there a simpler way? – kamilkp Sep 16 '16 at 14:49

1 Answers1

2

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:

Community
  • 1
  • 1
yurzui
  • 205,937
  • 32
  • 433
  • 399