Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 加载在angular2 final中动态创建的动态组件_Javascript_Angular - Fatal编程技术网

Javascript 加载在angular2 final中动态创建的动态组件

Javascript 加载在angular2 final中动态创建的动态组件,javascript,angular,Javascript,Angular,以前使用DynamicComponentLoader我可以这样写: import {Directive, Component, ViewContainerRef, DynamicComponentLoader} from '@angular/core'; @Directive({ selector: '[some-directive]' }) export class SomeDirective { costructor(dcl: DynamicComponentLoader, vie

以前使用
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
我看到了如下示例:

(这里讨论)

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

如何将临时创建的组件加载到视图中

我发现:
但是,要完成这样一项简单的任务,需要大量的代码。

这可能就是您想要的:

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

相关问题:


这里:是如何使用RuntimeCompiler并在Fly上生成动态模板和组件。我看到了它,这是我从中获得“工作”plunker链接的问题。但这是一个疯狂的代码量,以实现在angular2的前一个版本中用几行代码就可以实现的东西。难道没有更简单的方法吗?