首页 > 解决方案 > 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放入 aMatDialog时,我发现这个关于堆栈溢出的绝佳答案

深入研究一下这个答案:

此方法采用一个组件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. 我应该dynamic.create(TextComponent, config)为我冗长的Container开关方法提供更换服务吗?

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

标签: angular

解决方案


编写时不需要@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"

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


推荐阅读