我使用this.data.component
动态创建子组件resolveComponentFactory
:
export class MyDialogComponent implements OnInit, OnDestroy {
@ViewChild("target", { static: true , read: ViewContainerRef}) viewContainerRef: ViewContainerRef;
componentRef: ComponentRef<any>;
constructor(
private resolver: ComponentFactoryResolver,
@Inject(MAT_DIALOG_DATA) public data: any
) {}
ngOnInit() {
const factory = this.resolver.resolveComponentFactory(this.data.component);
this.componentRef = this.viewContainerRef.createComponent(factory);
}
ngOnDestroy() {
if (this.componentRef) {
this.componentRef.destroy();
}
}
}
子组件外观:
@Component({
selector: "simple-dict-word-dialog",
templateUrl: "./dictionarySimpleWord-dialog.component.html"
})
export class DictionarySimpleDialogComponent {
}
如何在子组件中访问对象this.data
?
我尝试过:
const factory = this.resolver.resolveComponentFactory(this.data.component);
this.componentRef = this.viewContainerRef.createComponent(factory);
this.componentRef.instance.type = "ok";
this.componentRef.instance.mode = {id: 1};
我的子组件是:
export class DictionarySimpleDialogComponent implements OnInit {
@Input() model: ClassificatorOrganizations;
@Input() type: string;
ngOnInit() {
console.log(this.type);
console.log(this.model);
}
}
所以,我无法获得:
console.log(this.type);
console.log(this.model);
它们是空的
答案 0 :(得分:1)
ComponentRef
具有instance
属性,它是您的子组件实例。您可以按照Angular 2 dynamically add component instance into container中的说明将数据传递给它。