Reputation: 99
I have a angular reactive form, where I want to add to fields on button click. So far I can add the fields on button click and it works. But there are two problems I do not really understand and do not have a idea.
Could someone look at it and give me a pointer maybe?
this is my ts file where I intialize my form:
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(''),
}));
}
This is my html (only the relevant part):
<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>
Upvotes: 0
Views: 2600
Reputation: 3613
I don't know, why you're use [(ngModel)]
with with FormGroup
in the same time.
Updated: The only one reason why you can't reset your form, it's because you're using [(ngModel)]. "Just guessing".
And you only reset your reactive form ("materialAddForm") and not template driven form ("ngModel").
That's why your value always still there.
You can check an example here: https://stackblitz.com/edit/angular-ivy-mzdm3r?file=src/app/app.component.ts
Upvotes: 2