【问题标题】:Angular: dynamic componentAngular:动态组件
【发布时间】:2019-07-12 14:24:11
【问题描述】:

我按照 Angular 文档动态生成组件:https://angular.io/guide/dynamic-component-loader。 这很好用,但现在我想在每个动态生成的组件周围添加一个包装器组件(稍后这个包装器应该包含一个工具栏)。但我现在不知道。

包装器组件:html 也是空的

export class ComponentWraperComponent implements OnInit {

  constructor() { }

  ngOnInit() {}

}

DynamicComponentBuilderComponent

export class DynamicComponentBuilderComponent implements OnInit, OnChanges {
  @Input() elementConfigs: IElementConfig[];
  @ViewChild(DynamicComponentPlaceholderDirective, { static: true }) placeholder: DynamicComponentPlaceholderDirective;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private dynamicComponentService: DynamicComponentService) { }

  ngOnChanges() {
    const viewContainerRef = this.placeholder.viewContainerRef;
    viewContainerRef.clear();

    if (this.elementConfigs && this.elementConfigs.length > 0) {
      this.elementConfigs.forEach((config: IElementConfig) => {
        const componentToCreate: any = this.dynamicComponentService.resolveComponent(config);
        LoggingHelper.debug("DynamicComponentBuilderComponent.ngOnChanges(), interating over element configs. Building component " + config.type);

        // Wrapper
        const componentWraperComponentFactory = this.componentFactoryResolver.resolveComponentFactory(ComponentWraperComponent);

        // Component
        const ComponentWraperComponent = this.componentFactoryResolver.resolveComponentFactory(componentToCreate);


**// Here I have both. The wrapper and component. But how can I add the component into the wrapper and than add the wrapper into the viewContainerRef?**


        const componentRef = viewContainerRef.createComponent(componentFactory);

      });
    }
  }

【问题讨论】:

    标签: angular


    【解决方案1】:

    假设您通过<ng-content> 将子组件放入“包装器”中。

    @Component({
        selector: 'wrapper-comp',
        template: '...toolbar... <ng-content></ng-content>'
    })
    export class WraperComponent {}
    

    那么你可以:

    1. 先创建子组件
    2. ViewContainerRef 上创建带有子组件的包装器组件

    例如:

    const childFactory: ComponentFactory<ChildComponent> = factoryResolver.resolveComponentFactory(ChildComponent);
    const childComp: ComponentRef<ChildComponent> = childFactory.create(this.injector);
    
    const wrapperFactory: ComponentFactory<WraperComponent> = factoryResolver.resolveComponentFactory(WraperComponent);
    
    const wrapperComp: ComponentRef<WraperComponent> = this.viewContainerRef.createComponent(
        wrapperFactory,
        0,
        this.injector,
        [[
            childComp.location.nativeElement
        ]]
    );
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2019-07-26
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2019-05-14
      • 2017-07-17
      相关资源
      最近更新 更多