目前,我有一个Container
组件,其中包含动态组件列表。每个动态组件都有一个@Input() config
属性。 Container
将使用一个开关处理数组,该开关看起来类似于TextComponent
switch (config.selector) {
case ComponentTypes.TEXT:
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(TextContentComponent);
const componentReference = viewContainerRef.createComponent(componentFactory);
const component = componentReference.instance;
component.config = config;
component.detectChanges();
return componentReference;
break;
}
当我寻找如何将Container
放入MatDialog
时,我发现了excellent answer on stack overflow
深入研究该答案:
此方法正在使用组件someComponent
。 (可能是我的Container
)。但是第二个参数似乎像我的config
。
this.dialogRef = this.dialog.open(someComponent, {
width: 330px,
height: 400px,
data: {
dataKey: yourData
}
});
尽管有趣的地方在someComponent
中。
import {MAT_DIALOG_DATA} from '@angular/material';
import { Inject } from '@angular/core';
constructor(
@Inject(MAT_DIALOG_DATA) public data: any
) { }
ngOnInit() {
// will log the entire data object
console.log(this.data)
}
问题
@Input
属性,但在这里他们选择了注入令牌。这几乎类似于new Container(config)
,但未记录。他们为什么不将数据视为@input
?dynamic.create(TextComponent, config)
切换方法提供Container
更换服务吗? PS:我要问的原因是,与知道数据是实例化的一部分相比,@Input
和ngOnChanges
不适用于动态组件可能会很痛苦。
答案 0 :(得分:0)
编写时不需要@Input
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '250px',
data: {name: this.name, animal: this.animal}
});
//You can use dialogRef.componentInstance to "get" the component
//e.g. if you has a variable in your Component: "anotherVariable"
dialogRef.componentInstance.anotherVariable="hello word"
注入数据,您可以在打开对话框时为“数据”赋值