Angular 12 尝试将数据传递给动态加载的组件,但不确定如何实现

Angular 12 trying to pass data to a dynamic loaded component, but uncertain on how to achieve it

我有一个正在动态加载的组件。

代码如下:

app.component.ts

    @ViewChild(InjectDirective, { static: true }) injectComp!: InjectDirective;
    
      componentFactory: any;
      constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    
      add(): void {
        this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(ModalComponent);
        const viewContainerRef = this.injectComp.viewContainerRef;
        viewContainerRef.createComponent(this.componentFactory);
      }

app.component.html

    <button (click)="add()">Dynamically Add Component</button>  
    <ng-template appInject></ng-template>

和指令:

    import { Directive, ViewContainerRef } from '@angular/core';
    
    @Directive({
      selector: '[appInject]'
    })
    export class InjectDirective {
    
      constructor(public viewContainerRef: ViewContainerRef) {}
    
    }

我需要将一些数据传递给动态加载的组件。

我该怎么做?

createComponent 函数正在返回组件的实例。您可以通过将此示例作为参数传递给指令来解决此问题。

app.component.ts

add(): void {
  this.componentFactory =
    this.componentFactoryResolver.resolveComponentFactory(ModalComponent);
  const viewContainerRef = this.injectComp.viewContainerRef;
  const component = viewContainerRef.createComponent<ModalComponent>(
    this.componentFactory
  );
  // pass component to directive
  this.injectComp.modalComponent = component.instance;
}

inject.directive.ts

@Input() set modalComponent(component: ModalComponent) {
   // You can pass parameter here
   component.zIndex = Math.random() * 10;
}

此处的示例项目:https://stackblitz.com/edit/angular-ivy-ooghrz?file=src%2Fapp%2Finject.directive.ts