angular - 角度反应式表单数组将第一个索引值作为空对象返回
问题描述
在我的 Angular 表单中,从一个表单移动到另一个表单时,formControl 无法呈现它的特定值,而是显示上次访问的表单值。
例如。如果我访问过product_id = 1
并且有formControl('productValue')
像10, 11, 12这样的值。现在我要移动到product_id = 2
那个时候它应该显示product_id = 2
相关值(45、89、63),但它会呈现以前访问过的product_id = 1
值,即10、11、12
import { Injectable } from "@angular/core";
import { FormGroup, FormBuilder, FormControl, FormArray } from "@angular/forms";
@Injectable({
providedIn: "root",
})
export class ProductService {
public productForm: FormGroup = this.fb.group({
inventoryCollection: new FormArray([
new FormGroup({ productStatus: new FormControl(""), productValue: new FormControl("") })
])
});
getInventoryData(productId) {
let controlsCollection = <FormArray>this.productForm.get('dataCollection')
this.getCollectionById(productId).subscribe((res: any) => {
res.forEach(data => {
controlsCollection.push(new FormGroup({
productStatus: new FormControl(data.status)
productValue: new FormControl(data.productValue)
}))
});
})
}
}
调用getInventoryData()
方法的组件
export class ProductComponent implements OnInit {
constructure(private router: Router) {
this.route.parent.params.subscribe(params => {
this.params = { id: Number(params['id']) }
})}
ngOnInit() {
this.productService.getInventoryData(this.params.id)
}
}
HTML表单如下:
<form [formGroup]="productService.productForm">
<div formArrayName="dataCollection">
<div [formGroupName]="i" *ngFor="let element of details; let i = index">
<input matInput type="text" formControlName="productValue">
<mat-select formControlName="productStatus" value="{{productService.details[i].productStatus === '0' ? 'Active' : 'Inactive'}}">
<mat-option value="AC">Active</mat-option>
<mat-option value="IA">Inactive</mat-option>
</mat-select>
</div>
</div>
</form>
PS:我访问过product_id = 1”和“moving to product_id = 2”的意思是路由器导航。
http://localhost:4500/product/1/collection i.e product_id = 1
http://localhost:4500/product/2/collection i.e product_id = 2
解决方案
推荐阅读
- bash - SED 搜索文本块并在该文本块的末尾添加文本
- reactjs - 使用带有 Typescript 和 React 的 Abort Signal 删除事件处理程序
- r - 如何选择特定“目标”的网页的“href”?
- bash - 文本文件内容匹配 if else 图片分辨率
- django - 为什么不能创建超级用户
- node.js - 构建时将 ts-node package.json 脚本转换为 nodejs package.json 脚本
- reactjs - React i18-next - 为什么使用 i18next-http-backend 而不是导入?
- python - I am struggling with understanding the following list comprehension
- networking - VMWare,无法通过桥接连接从 Windows 10 主机 ping Linux 来宾
- .net-core - 从 .Net Core 调用框架方法时找不到库