arrays - Angular 8 和 FormArrays 如何初始化下拉列表以选择数组附带的初始值
问题描述
我有一个下拉列表,用户可以从中选择多个项目,并且项目将被附加到一个数组中selectedInvoicesArray
:
Object.keys(selectedInvoices).forEach((key, index)=>{
this.selectedInvoicesArray.push(this.invoicesList.filter(res => {
return res.invoice_id == selectedInvoices[key]
}));
})
在 html 端,我们有一个*ngFor
循环selectedInvoicesArray
数组并将每个索引的信息显示到一个 div 中。
我需要的是显示一个下拉列表,其中包含Active
和Inactive
作为选项,一旦每个项目的部分显示在组件上,就会选择原始值,然后用户可以更改状态。
唯一的方法是使用FormArray
.
所以我做了以下事情:
我创建了一个包含表单数组的表单组:
<form [formGroup]="updateStatusForm">
<mat-form-field *ngFor="let select of selectedInvoicesArray; let i = index">
<mat-select [formControlName]="i">
<mat-option *ngFor="let status of invoiceStatuses" [value]="status.id">{{status.name}}</mat-option>
</mat-select>
</mat-form-field>
</form>
然后,我创建了 formGroup 脚本:
updateStatusForm: FormGroup;
createUpdateStatusForm(){
this.updateStatusForm = this.fb.group({
'statusesControl': new FormControl('')
})
}
createUpdateStatusForm()
每次将新数组推入时,我都会调用selectedInvoicesArray
:
Object.keys(selectedInvoices).forEach((key, index)=>{
this.selectedInvoicesArray.push(this.invoicesList.filter(res => {
return res.invoice_id == selectedInvoices[key]
}));
this.createUpdateStatusForm()
})
正如您在图像中看到的,下拉列表是空的。我需要将其设置为来自数组的初始值。
*ngFor
正在迭代的内容selectedInvoicesArray
如下:
<div *ngFor="let invoice of selectedInvoicesArray;let i = index;">
作为一个例子:
<div>
Description: {{invoice[0].description}}
</div>
当我将 2 个或更多数组推入selectedInvoicesArray
时,在每个部分中我都会看到 2 个或更多下拉列表:
但我无法设置每个生成的表单数组的初始值来显示名为is_active
.
编辑
我接下来尝试的是循环selectedInvoicesArray
并设置每个生成的表单数组的值:
Object.keys(this.selectedInvoicesArray).forEach(key=>{
console.log(this.selectedInvoicesArray[key].invoices[0])
this.createUpdateStatusForm(this.selectedInvoicesArray[key].invoices[0].is_active);
})
和:
createUpdateStatusForm(status_id){
this.updateStatusForm = this.fb.group({
'statusesControl': new FormControl(status_id)
})
}
但我有以下错误:
无法读取 FormGroupDirective.addControl 处未定义的属性“获取”
解决方案
推荐阅读
- r - 从 lpSolve 转换为 lpSolveAPI 包
- tensorflow - 在自定义 tensorflow keras 指标中获取批量大小
- c++ - 将命令行上的输入显示到数组中时如何删除./a.out?
- r - Random Forest does not accept feature names
- ios - 尝试以编程方式将 UIScrollView 添加到我的应用程序中,但我一直得到一个空白视图
- c++ - 从指针发送这样的参数有什么区别
- pandas - 在数据框的索引中收集每年的相同月份
- ajax - POST请求没有响应Spring boot - AJAX
- c# - C# UWP WebView 未出现在 UWP 主页上
- xcode - 归档期间 Firebase Admob 构建失败