角材料对话框“数据”如何工作?

时间:2019-04-16 10:24:00

标签: angular

目前,我有一个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)
}

问题

  1. 那里发生了什么?似乎是一种未列出的创建动态组件的方法,似乎比我使用的方法更省事。
  2. 我期望有一个@Input属性,但在这里他们选择了注入令牌。这几乎类似于new Container(config),但未记录。他们为什么不将数据视为@input
  3. 我应该为long绕的dynamic.create(TextComponent, config)切换方法提供Container更换服务吗?

PS:我要问的原因是,与知道数据是实例化的一部分相比,@InputngOnChanges不适用于动态组件可能会很痛苦。

1 个答案:

答案 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"

注入数据,您可以在打开对话框时为“数据”赋值

相关问题