首页 > 解决方案 > 以与所需返回值不同的格式设置 mat-select 的初始值

问题描述

你好 Stackoverflow 社区,

我正在尝试使用特定值初始化表单控件,但我找不到满足我要求的方法。我有以下代码:

HTML 模板:

<mat-form-field>
  <mat-select formControlName='businessUnit'>
    <mat-option *ngFor="let businessUnit of businessUnitsArray" [value]="[businessUnit.id, businessUnit.costCenter]">{{businessUnit.businessUnitName}}</mat-option>
  </mat-select>
</mat-form-field>

打字稿组件:

this.updateDepartmentForm = this.formBuilder.group({
  departmentName:   [this.dialogData.departmentName, Validators.required ],
  departmentNumber: [this.dialogData.departmentNumber, Validators.required ],
  businessUnit:     [this.dialogData.businessUnitInfo[1], Validators.required ]
});

this.dialogData.businessUnitInfo[1]包含一个等于我希望在表单初始化时最初选择的mat-option的字符串。我知道,为了实现这一点,我必须将mat-option的 [value] 标记的值更改为我想要的数据,在这种情况下this.dialogData.businessUnitInfo[1]

但是,我的问题是,在提交表单时,我想要返回的与所选mat-option相关的数据不是所选选项的字符串,而是包含所选选项的 id 和 costCenter 的数组,它们是两个链接的变量到选定的mat-option,这就是为什么我需要保持 [value] 标记等于数组 --> [businessUnit.id, businessUnit.costCenter]。

在按原样编写代码的情况下,mat-select不会被初始化为任何值。有什么办法可以做到这一点?

感谢大家的支持

标签: angularangular-material

解决方案


您正在尝试使用动态创建的数组作为选定值。通过引用检查数组相等性,因此无论您为表单控件提供什么值,它都不会与任何选项值匹配。你可以做的是:

  1. 不使用数组,只使用 id 作为选定值
  2. 使用预定义的数组数组并在数组中设置选定的值

由于 1. option 很清楚,这里是 2. option 的示例:

this.businessSelections = this.businessUnitsArray.map(bu=> [bu.id, bu.costCenter]); // initialize a property with an array of arrays

在您的模板中:

<mat-form-field>
  <mat-select formControlName='businessUnit'>
    <mat-option *ngFor="let businessUnit of businessUnitsArray;let ix = index"
                  [value]="businessSelections[ix]">
                 {{businessUnit.businessUnitName}} 
    </mat-option>
  </mat-select>
</mat-form-field>

设置初始值:

this.updateDepartmentForm.patchValue({ businessUnit : this.businessSelections[0] })
// or query your array with the parameter you passed to your dialog
const buId = dialogData.businessUnitInfo[0]; // it contains id i think
const selected = this.businessSelections.find(r=> r[0] === buId); // find the selection with the id
this.updateDepartmentForm.patchValue({ businessUnit : selected });

推荐阅读