加载在angular2final中动态创建的组件

Load dynamic component created on the fly in angular2 final

本文关键字:创建 组件 动态 angular2final 加载      更新时间:2023-09-26

以前使用DynamicComponentLoader时,我可以这样写:

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');
      });
    });
  }
}

现在使用angular2 final和NgModules,我看到这样的例子:http://plnkr.co/edit/P0spNzu8JbQad2aKACsX?p=info

(此处讨论https://github.com/angular/angular/issues/10735)

动态加载HelloComponent,但它需要在创建根NgModule时预先声明HelloComponent。

我如何加载一个特别创建的组件到我的视图?

我发现这个:http://plnkr.co/edit/wh4VJG?p=preview但是,要完成这样一个简单的任务,代码量实在是太大了。

这可能就是你要找的:

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);
      });
  }
}

参见live Plunker

相关问题:

    Angular2 RC6 -从模块动态加载组件