1

I followed the Angular documentation to generate Components dynamically: https://angular.io/guide/dynamic-component-loader. This works fine, but now I would like to add a wrapper component around each dynamically generated component (later this wrapper should contain a toolbar). But I don't now how.

Wrapper component: still empty also the 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);

      });
    }
  }

1 Answer 1

1

Assume you put a child component into the "wrapper" via <ng-content>.

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

then you could:

  1. create the child component first
  2. create the wrapper component with child on ViewContainerRef

for example:

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
    ]]
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.