angular - 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!
解决方案
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
我认为这将解决您的问题。如果你把它写在一个服务函数中,那么你也可以从其他地方调用它。
推荐阅读
- python - 使用 Python 进行 DNA 到 RNA 转换:如何在不替换/更改预先替换的输入的情况下替换文本输入?
- sql - 从一个范围内每年提取价值
- python - 如何从 azure ml 服务数据集中访问文件或文件夹?
- conditional-statements - TYPO3 10.4 LTS 中的嵌套数组条件
- python - 过滤低于阈值的连续的
- javascript - Discords.js 向服务器中的每个通道发送消息
- excel - 从第一个到最后一个连接,但在另一列中连接
- bluetooth-lowenergy - 如何在 Linux 内核 3.10.0 版本中启用或反向移植蓝牙 BLE 功能?
- python - 在实感中共享上下文时进程冻结
- python - 如何使用 rpython 翻译器将我的 python 脚本转换为 pypy?