动态加载现有组件Angular 2 Final Release

时间:2016-09-24 17:15:22

标签: javascript angular typescript

我正在尝试在最终版本2.0.0中动态加载组件。

使用RC5我使用以下代码加载:

创建一个指令来加载控件:

import {
  CheckboxComponent, CheckboxListComponent,DatePickerComponent
} from '../components/';

@Directive({
      selector: '[ctrl-factory]'
    })
    export class ControlFactoryDirective implements OnChanges {
      @Input() model: any;

      constructor(private vcRef: ViewContainerRef, private resolver: ComponentResolver) {
      }

      create(cp) {
        this.resolver.resolveComponent(cp)
          .then(factory => {
            const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
            this.vcRef.createComponent(factory, 0, injector, []);
            let ch = this.vcRef.createComponent(factory, 0, injector, []).instance;
            ch.model = this.model;
        });
      }

      ngOnChanges() {
        if (!this.model) return;

        switch (this.model.type) {
          case 'checkbox':
            this.create(CheckboxComponent);
            break;
          case 'checkboxlist':
            this.create(CheckboxListComponent);
            break;
          case 'datepicker':
            this.create(DatePickerComponent);
            break;
          default:
            break;
        }
      }
    }

然后在我的页面中加载了该指令,如下所示:

<div ctrl-factory *ngFor="let child of page.childrens" [model]="child"></div>

但是从rc5更新到2.0.0最终版本后,解析器不再存在,被编译器取代。

我发现大量的地方显示了如何使用不同的代码加载它,但所有那些太复杂,我无法使其工作。

以此为例:How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

它看起来更具体到那个场景,我只需要加载组件并设置一个名为model的@Input。

当我尝试时,我必须为每个组件动态创建一个模块,然后将组件添加到它。但后来我遇到的问题是该组件被设置在多个模块中,尝试在某些地方删除不起作用。

显示的代码的主要部分,我来自此链接:http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2-rc-5/

做了一些改变。

  

更新

我设法使用以下方法使其工作:

创建方法已更改为

private create(cp) {
    @NgModule({
      imports: [BrowserModule, ControlsModule],
      declarations: []
    })
    class DynamicModule {}

    this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
      .then(({componentFactories}) => {
        const compFactory = componentFactories.find(x => x.componentType === cp);
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        const cmpRef = this.vcRef.createComponent(compFactory, 0, injector, []);
        cmpRef.instance.model = this.model;
      });
  }

我找到的大多数地方,设置创建组件并将其设置为DynamicModule,问题是当你已经在另一个模块中声明相同的组件时,angular会抱怨。在我的例子中,解决方案是导入我的ControlsModule,它控制了我的所有控件。

2 个答案:

答案 0 :(得分:12)

更新

4.0.0-beta.3 https://github.com/angular/angular/commit/8578682

引入了

NgComponentOutlet

  

即将推出NgComponentOutlet

我认为有两种选择:

1)使用 ComponentFactoryResolver

它使用已经生成的工厂,代码如下所示:

constructor(private vcRef: ViewContainerRef, private resolver: ComponentFactoryResolver) { }
create(comp) {
  const factory = this.resolver.resolveComponentFactory(comp);
  const compRef = this.vcRef.createComponent(factory);

  (<any>compRef).instance.model = this.model;
}

在这种情况下,我们必须在模块的decorator中的declarationsentryComponents属性中定义动态组件

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, DynamicComponent ],
  entryComponents: [DynamicComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

2)使用编译器

在这种情况下,我们只能使用compiler.compileModuleAndAllComponentsAsync运行模块编译,然后从componentFactories数组中查找组件。您的指令可能如下所示:

constructor(private vcRef: ViewContainerRef, private loader: DynamicLoaderService) { }

create(comp) {
  this.loader.createComponentFactory(comp).then(factory => {
     const compRef = this.vcRef.createComponent(factory);

    (<any>compRef).instance.model = this.model;
  })
}

DynamicLoaderService是一个加载和存储组件工厂的全局服务。

@Injectable()
export class DynamicLoaderService {
  constructor(protected compiler: Compiler) {}

  private resolveCompHelper$ = new Subject<any>();
  private cache = new Map<string, ComponentFactory<any> | number>();

  public createComponentFactory(type: string) : Promise<ComponentFactory<any>> {
    let factory = this.cache.get(type);

    // if factory has been already loading
    if(factory === 1) {
      return new Promise((resolve) => {
        // waiting compilation of factory
        const subscriber = this.resolveCompHelper$.subscribe((data) => {
          if(type !== data.type) return;
          subscriber.unsubscribe();
          resolve(data.factory);
        });   
      });
    } 
    // factory exists in cache
    if (factory) {
      return new Promise((resolve) => resolve(factory));
    }

    const comp = typeMap[type];
    // factory startes loading
    this.cache.set(type, 1);
    return new Promise((resolve) => {
      this.compiler.compileModuleAndAllComponentsAsync(createComponentModule(comp))
        .then((moduleWithFactories: ModuleWithComponentFactories<any>) =>  {
            factory = moduleWithFactories.componentFactories
              .find(x => x.componentType === comp);
            this.cache.set(type, factory);
            this.resolveCompHelper$.next({ type, factory});

            resolve(factory);
        });
    });
  }
}

<强> Plunker Example

希望它可以帮到你!

答案 1 :(得分:0)

根据指令看到这个选项对我很有用,但我根据组件找到了符合我需求的选项:https://www.ag-grid.com/ag-grid-angular-aot-dynamic-components/

快乐的编码!