首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角度:动态组件

角度:动态组件
EN

Stack Overflow用户
提问于 2019-07-12 22:24:12
回答 1查看 60关注 0票数 1

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

包装器组件:仍然是空的,也是html

代码语言:javascript
复制
export class ComponentWraperComponent implements OnInit {

  constructor() { }

  ngOnInit() {}

}

DynamicComponentBuilderComponent

代码语言:javascript
复制
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);

      });
    }
  }
EN

回答 1

Stack Overflow用户

发布于 2019-07-13 02:24:18

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

代码语言:javascript
复制
@Component({
    selector: 'wrapper-comp',
    template: '...toolbar... <ng-content></ng-content>'
})
export class WraperComponent {}

然后,您可以:

ViewContainerRef上,

  1. 创建子组件首先
  2. 创建包含子组件的包装组件

例如:

代码语言:javascript
复制
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
    ]]
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57008963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档