0

I pass parameter component to angular element ,and I want to render this component in this custom element.

Here is the code for the target repository, which uses element

<mf-element1
  [getComponent]="getTargetComponent.bind(this)">
</mf-element1>

ts

export class DynamicComponent {
  constructor(public component: Type<any>, public data: any) {}
}


 targetComponent = new DynamicComponent(PccComponent2Component, {})
 

  getTargetComponent(): DynamicComponent{
    return this.targetComponent;
  }

Here is the code for the element repository

@Directive({
  selector: '[appAd]'
})
export class AdDirective {
  constructor(public viewContainerRef: ViewContainerRef) {}
}

html

<ng-template appAd></ng-template>

ts

 @ViewChild(AdDirective, {static: true}) adHost!: AdDirective;
  pccComponent!: DynamicComponent;
  pccService!: PccServiceService;
  @Input() getComponent!: () => DynamicComponent;
  @Input() getService!: () => PccServiceService;
  title = '';
  constructor(private componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit(): void {
    this.pccService = this.getService();
    this.title = this.pccService.title;
    this.pccComponent = this.getComponent();
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.pccComponent.component);
    const viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();
    const componentRef = viewContainerRef.createComponent<AdComponent>(componentFactory);
    componentRef.instance.data = this.pccComponent.data;
  }

source code is https://gitee.com/hjxiaoqianduan/el1.git and https://gitee.com/hjxiaoqianduan/pcc.git

0 Answers0