angular - 使用 Angular 5 动态创建组件

标签 angular typescript angular5

我一直在使用这样的代码在我的应用程序中动态创建组件。这些组件必须支持动态输入。但现在我尝试更新到 Angular 5 并且 ReflectiveInjector 已被弃用。如果有人知道如何帮助我在 Angular 5 中重用它,我将非常感激...

import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver} from '@angular/core';
import {
  AComponent,
  BComponent,
  CComponent
} from './';

@Component({
  selector: 'dynamic-component',
  entryComponents: [
    AComponent,
    BComponent,
    CComponent
  ],
  template: `
    <div #dynamicComponentContainer></div>
  `
})
export class DynamicComponent {

  currentComponent = null;

  @ViewChild('dynamicPriceItemComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;

  @Input() set componentData( data: { component: any, inputs: any }) {
    if (!data) {
      return;
    }

    let inputProviders = Object.keys(data.inputs).map((inputName) => {
      return { provide: inputName, useValue: data.inputs[inputName] };
    });

    let resolvedInputs = ReflectiveInjector.resolve(inputProviders);

    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicPriceItemComponentContainer.parentInjector);

    let factory = this.resolver.resolveComponentFactory(data.component);

    let component = factory.create(injector);

    this.dynamicComponentContainer.insert(component.hostView);

    if (this.currentComponent) {
      this.currentComponent.destroy();
    }

    this.currentComponent = component;
  }

  constructor(private resolver: ComponentFactoryResolver) {

  }
}

最佳答案

May this give some clue.

constructor(private renderer: Renderer2,
            private viewContainerRef: ViewContainerRef,
            private componentFactoryResolver: ComponentFactoryResolver) {

}

private createdDynamicComponent(): void {
    const factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
    const createdComponentComponent = this.viewContainerRef.createComponent(factory);
    this.renderer.appendChild('element where you want append', createdComponentComponent.location.nativeElement);
}

关于angular - 使用 Angular 5 动态创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573563/

相关文章:

angularjs - 使用 Angular5 进行服务器端渲染(从 AngularJS 迁移)

typescript - mat-option需要2次点击事件来加载异步数据

html - Angular 6 iframe 绑定(bind)

angular - 改进 Angular 7 应用程序的生产构建时间

javascript - 错误 TS2339 : JavaScript to Typescript error

angular - 如何在不保留选项卡的选项卡之外设置根页面?

javascript - 如何使用 React 和 Typescript 处理 div 上的点击事件

angular - 通过 child 向孙子注入(inject)祖先的前向引用

angular - ag-Grid:找不到 agRichSelectCellEditor

javascript - Angular 输入更新验证器