Reputation: 483
I have a form. In the typescript I have an array of quantity materials that are added or removed from an inventory. Which is displayed in the html by an ngFor.
What I am looking for is that in the FormControl, I can add several values depending on the materials.
That is, if I have X materials, something like [material 1, material 2, material 3]
appears in the same formControl. Since I don't know how many materials are added.
Same for the code of the new material and the old material. I don't know if I'm making myself understood. But this is my code.
<div class="row" *ngFor="let material of materials">
<mat-form-field class="col-md-4">
<mat-select required placeholder="Select Material" formControlName="materials">
<mat-option *ngFor="let object of objects" [value]="object">
{{ object }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="col-md-4">
<input matInput type="text" formControlName="new" />
<mat-label>Code New Material</mat-label>
</mat-form-field>
<mat-form-field class="col-md-4">
<input matInput type="number" formControlName="old" />
<mat-label>Code Old Material</mat-label>
</mat-form-field>
</div>
<div class="row mb-2 d-flex justify-content-center">
<div class="col-xs-12 col-md-4 mb-2">
<button
mat-raised-button
color="primary"
class="btn bnt-primary btn-block"
(click)="addMaterial()"
>
<mat-icon>add</mat-icon>
<span> Add Material</span>
</button>
</div>
<div class="col-xs-12 col-md-4">
<button
mat-raised-button
color="warn"
class="btn bnt-primary btn-block"
(click)="removeMaterial()"
>
<mat-icon>remove</mat-icon>
<span> Remove Material</span>
</button>
</div>
</div>
And this is my typescript
export class MaterialComponent implements OnInit {
materials: number[] = [1];
objects: string[] = ['MATERIAL 1', 'MATERIAL 2','MATERIAL 3', 'MATERIAL 4'];
form: FormGroup;
constructor(private formBuilder: FormBuilder,){
}
ngOnInit(): void {
this.makeForm();
}
makeForm() {
this.form = this.formBuilder.group({
materials: [''],
new: [''],
old: [''],
});
}
addMaterial(){
this.materiales.push(1);
}
removeMaterial(){
this.materiales.pop();
}
}
If I do console.log(this.form.get('materials').value)
It only gets the first value. I would like to take all the values for each Input of the ngFor
Upvotes: 1
Views: 8165
Reputation: 1116
According to your question user will add or remove materials using a button then you want to update a form control according to the elements in the array on that specific time.This can be achieved by using patch functionality to form control after push or pop operation.
addMaterial(){
this.materiales.push(1);
//Update what ever the formcontrol you want here as per requirement
this.form.patchValue({
materials: function (){
let temp = "",
this.materials.forEach(index,value){
temp += value;
}
return temp;
}
});
}
removeMaterial(){
this.materiales.pop();
//Update what ever the formcontrol you want here as per requirement
this.form.patchValue({
materials: this.materials
});
}
Upvotes: 1