首页 > 解决方案 > Angular 将数据注入到动态组件中 @inputs 被传递给 mat-dialog 组件

问题描述

我有一种情况,我需要在动态对话框组件内显示动态表格组件。

动态对话框可以接收要在其中显示的另一个组件。这是通过 MatDialogConfig 数据属性完成的。

这是在我的对话框的模板中:

<ng-container *ngComponentOutlet="dialogPassedPayload.additionalData"></ng-container>

这确保了传入的组件,仅在提供组件时才添加 dom。这一切都按预期工作。当我需要将数据输入到传递的组件的输入中时,就会出现问题。我的动态表 comp 需要提供多个 @input 属性才能运行。

我试图通过这样的 Injector 来实现这一点:

let myInjector: Injector;
myInjector = ReflectiveInjector.resolveAndCreate(
  [{
      provide: DATA,
      useValue: [{
        someProp: "data1"
      }, {
        someProp: "data2"
      }]
    },
    {
      provide: MUTATORARRAY,
      useValue: []
    },
    {
      provide: HIDDENPROPS,
      useValue: []
    },
    {
      provide: SHOWSELECTCOLUMN,
      useValue: []
    },
    {
      provide: SHOWEDITCOLUMN,
      useValue: []
    }
  ],
  myInjector
);

const dialogConfig = new MatDialogConfig();
let dialogConfigModel: DialogConfigModel = {
  dynamicFormModel: [],
  additionalData: DataTableComponent,
  dialogTitle: "Change Items(s) Status"
};
dialogConfig.width = this.dialogWidthNormal;
dialogConfig.data = dialogConfigModel;

const dialogRef = this._dialog.open(DynamicDialogComponent, dialogConfig);

我将注射器放在我的提供者中:

providers: [
    { provide: DATA, useValue: "" },
    { provide: MUTATORARRAY, useValue: "" },
    { provide: HIDDENPROPS, useValue: "" },
    { provide: SHOWSELECTCOLUMN, useValue: "" },
    { provide: SHOWEDITCOLUMN, useValue: "" }
]

但是……现在我该怎么办?数据不会注入到组件中,因为我不相信注入器链接到我的DataTableComponent。我相信注射器缺少一步。我在这里关注了这个:这里

编辑:

我注意到我没有将注射器添加到出口:

<ng-container *ngComponentOutlet="dialogPassedPayload.additionalData"></ng-container>

所以我将它传递到对话框中并将其更改为:

<ng-container *ngComponentOutlet="dialogPassedPayload.additionalData; injector: dialogPassedPayload.injector"></ng-container>

但是现在每当我打开对话框时都会收到此错误:

ERROR Error: No provider for ComponentFactoryResolver!

标签: angularangular-material

解决方案


const compFactory = this.compFactRes.resolveComponentFactory(ComponentClassName);
const compRef = compFactory.create(this.injector);
const compInstance: any = compRef.instance;
compInstance.data = data; //you can pass data here
this.appRef.attachView(compRef.hostView);
const compElement = (compRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; // here you are getting the component html you can append it to anywhere in the angular app

我认为这将解决您的问题。如果你把它写在一个服务函数中,那么你也可以从其他地方调用它。


推荐阅读