I am working with a component that includes a select option and a text input field. The purpose of the "select" is to choose a description of an object, while the input field is used to specify the quantity assigned to the selected object. In my form, I need to be able to select multiple objects along with their respective quantities. Each time I select an object and assign a quantity to it, I want to save this information in an object and display it as a chip.
However, I am facing an issue where every time I perform this action, all the items in the collection are replaced by the last one added.
Note: Angular CLI: Version 13.0.2 | npm 8.1.0
anotherWork = new workModel();
anotherMaterial = new materialModel();
anotherMaterialList = new Array<materialModel>();
//FORM CONTROLS
clientControl = new FormControl();
descriptionControl = new FormControl();
costControl = new FormControl();
employeesControl = new FormControl();
materialsControl = new FormControl();
isFinishedControl = new FormControl();
//[...
//...
//...]
materialDescriptionChange(desc:string){
this.anotherMaterial.description = desc;
}
materialQuantityChange(quan:string){
this.anotherMaterial.quantity = parseFloat(quan);
}
addMaterial(id:string){
this.anotherMaterial.id = id;
this.anotherMaterialList.push(this.anotherMaterial);
console.log(this.anotherMaterialList);
}
<!--MATERIALES | CHIPS / SELECT / INPUT NUMBER / BUTTON-->
<p>
<mat-form-field class="form-field" *ngIf="anotherMaterialList.length > 0">
<mat-chip-list >
<mat-chip *ngFor="let wmt of anotherMaterialList" >
{{wmt.description}} ({{wmt.quantity}})
</mat-chip>
</mat-chip-list>
</mat-form-field>
</p>
<p *ngIf="materialList !== undefined">
<mat-form-field appearance="legacy" class="form-field-material-select">
<mat-label>Materiales</mat-label>
<mat-select #ma [formControl]="materialsControl" (selectionChange)="materialDescriptionChange(ma.triggerValue)">
<mat-select-trigger>
<span *ngIf="materialsControl.value?.length > 0">
{{ma.triggerValue}}
</span>
</mat-select-trigger>
<mat-option *ngFor="let m of materialList" [value]="m.id">
{{m.description}} ({{m.quantity}})
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="legacy" class="form-field-material-input">
<mat-label>Cantidad</mat-label>
<input #q matInput placeholder="Cantidad" type="number" (change)="materialQuantityChange(q.value)" >
</mat-form-field>
<a (click)="addMaterial(ma.value)" color="primary" mat-raised-button class="form-field-material-button">
<mat-icon>add</mat-icon>
</a>
</p>
Sequence in images
1 - First step, before adding an object
5 - Evolution of the object displayed in the browser inspector