angular - 以与所需返回值不同的格式设置 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不会被初始化为任何值。有什么办法可以做到这一点?
感谢大家的支持
解决方案
您正在尝试使用动态创建的数组作为选定值。通过引用检查数组相等性,因此无论您为表单控件提供什么值,它都不会与任何选项值匹配。你可以做的是:
- 不使用数组,只使用 id 作为选定值
- 使用预定义的数组数组并在数组中设置选定的值
由于 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 });
推荐阅读
- java - 附加到带有 POI 的 excel 文件而不读取数据
- reactjs - 反应js渲染功能中的状态为空白
- angular-cli - 角度实时变化
- javascript - 根据下拉选择更改标题(标签)
- jquery - 使用 Jquery 获取响应
- angular - 我如何使用 catchError() 并且仍然返回带有 rxJs 6.0 的类型化 Observable?
- docker - 我可以在容器中使用无限循环而不是 cron
- c++ - c++ 应用程序在执行递归函数时崩溃
- python - 在没有 Windows 专有工具的情况下向现有 xlsx 添加密码(无人值守)
- c++ - 如何从文件中读取结构指针的动态分配链表?