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.

2
  • 1
    Here: How can I use/create dynamic template to compile dynamic Component with Angular 2.0? is how to use RuntimeCompiler and produce dynamic templates and components on the fly Commented Sep 16, 2016 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? Commented Sep 16, 2016 at 14:49

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.