在我的 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