I'm currently working on a form that involves managing an array of quantity materials in TypeScript. These materials can be added or removed from an inventory and are displayed in the HTML using ngFor. My goal is to allow the FormControl to accommodate multiple values based on the materials added, without knowing the exact number beforehand. The same challenge applies to distinguishing between new material codes and old material codes within the form. The code snippet below outlines my approach.
<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>
Here's how I'm handling this in my TypeScript file:
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.materials.push(1);
}
removeMaterial() {
this.materials.pop();
}
}
When I use
console.log(this.form.get('materials').value)
, it only retrieves the first value. How can I capture all the values for each input generated by ngFor?