【发布时间】:2021-01-02 00:00:59
【问题描述】:
我有一个角度反应形式,我想在按钮单击时添加到字段中。到目前为止,我可以在按钮单击时添加字段并且它可以工作。但是有两个问题我不是很了解,也没有想法。
- 问题是,我只能写一封信,然后就不能继续了
- 问题是在我关闭表单所在的模式后,我希望重置完整的表单。我在保存时完成了它,并且对于输入的值它有效。但不适用于添加的输入字段。他们总是留下来。
有人可以看看它并给我指点吗?
这是我初始化表单的 ts 文件:
ngOnInit() {
this.materialAddForm = this.fb.group({
name: new FormControl(''),
materialCode: new FormControl(''),
materialType: new FormControl(''),
quantity: new FormControl(''),
buyInformation: this.fb.array([])
})
}
saveMaterial() {
this.materialService.addMaterial(this.materialModel).subscribe(console.log) ;
this.materialAddForm.reset()
console.log(this.materialModel)
}
addSellerInput() {
const buyInformation = this.materialAddForm.controls.buyInformation as FormArray;
buyInformation.push(this.fb.group({
seller: new FormControl(''),
price: new FormControl(''),
}));
}
这是我的 html(仅相关部分):
<div class="form-row mb-4" formArrayName="buyInformation"
*ngFor="let buyInformation of materialAddForm.controls['buyInformation']?.value; let i = index">
<div class="input-group input-group-sm col-12 col-md-6 mb-4" [formGroupName]="i">
<div class="input-group-prepend">
<span class="input-group-text" id="sellerName">Seller Name</span>
</div>
<input type="text" class="form-control" aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
formControlName="seller"
>
</div>
<div class="input-group input-group-sm col-12 col-md-6 mb-4" [formGroupName]="i">
<div class="input-group-prepend">
<span class="input-group-text" id="materialUnitPrice">Price</span>
</div>
<input type="text" class="form-control" aria-label="Sizing example input"
aria-describedby="inputGroup-sizing-sm"
formControlName="price"
[(ngModel)]="materialModel.price" name="price">
</div>
</div>
</div>
【问题讨论】:
-
为什么你使用反应形式的 [(ngModel)]="materialModel.price"?您可以删除它并尝试。
-
我使用 ngModel 的原因是我想将 Inputs 的值与我的模型连接起来,并将其发送回我的后端,否则我不知道该怎么做。你有更好的解决方案吗?
-
我刚刚在所有地方删除了 ngModel,但仍然遇到同样的错误
标签: angular typescript angular-reactive-forms