Is there a glitch in the angular binding mechanism?

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

2 - Object added

3 - Adding second object

4 - Adding third object

5 - Evolution of the object displayed in the browser inspector

Answer №1

It appears that you are constantly using the same object reference. To avoid this, consider creating a new object each time you need to add one instead of reusing this.anotherMaterial:

addMaterial(id:string) {
  const material = new materialModel()
  material.id = id;
  material.description = this.anotherMaterial.description;
  material.quantity = this.anotherMaterial.quantity;
  this.anotherMaterialList.push(material);
  console.log(this.anotherMaterialList);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unraveling URLs in JSON with TypeScript

After retrieving a Json string from the BE API, I am parsing it into an array of Products[]. This collection is structured as follows: class Products { ProductId: number; ProductName: string; Price: number; ProductUrl: string; } The issue I' ...

Can you help me identify any issues with this code for uploading an image and quickly displaying it in Angular?

Located within the profile.component.html file <label for="profile">Profile Photo</label> <input type="file" [(ngModel)]='uploadedPhoto'/> <img [src]='uploadedPhoto'> Contained in the profile.component.ts file ...

Angular Material "search bar" component

I'm currently using angular material 10.x and trying to find a search component that matches the material design guidelines here: https://material.io/archive/guidelines/patterns/search.html#search-in-app-search So far, I've had no success with ...

Issue with PrimeNG p-editor Appearance

My text editor is not displaying correctly on my website. Please refer to the following images for reference: Top of the page Bottom of the page Currently, it only shows a large SVG and a few input fields at the bottom. The technologies I am using includ ...

Issue encountered: Unable to locate module - Error: Unable to resolve '@angular/core'

After completing all the installations, I attempted to run the repository angular2-webpack-starter. However, when executing the commands npm start or webpack, I encountered the following errors: Error messages related to missing modules: ... (list of var ...

How can certain properties be mandated while still permitting additional ones?

I am currently working on creating a function that requires one property as an argument, but could potentially have additional properties as well. Here is an example: interface Foo { bar: string; } function someFunc(obj) { // implement functional ...

Can you guide me on utilizing the drag and drop functionality in Angular 8 CDK to merge two cards together?

My current challenge involves attempting to drag one card over another card in order to effectively "merge" or "combine" them, similar to the action of dragging an image onto a folder on a desktop. Despite utilizing HTML5 native drag and drop functionalit ...

Guide: Populating an MUI Autocomplete TextField using data fetched from Axios

I have created a registration form for pets which includes an MUI Autocomplete component in the text field for selecting the pet type. However, I am facing an issue when trying to pre-fill the Autocomplete component with data from the database while edit ...

Utilizing Typescript and RequireJS for Incorporating jqueryui

Recently, I've been encountering issues with getting jQueryUI to function properly. Strangely enough, prior to attempting to integrate jQueryUI, using jQuery alone worked perfectly fine. The current problem I'm facing is receiving a "TypeError: ...

Guide to separating the bytes of a number and placing them into an Uint8Array

I am looking to convert a JavaScript number into the smallest possible uint8array representation. For example : 65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111]) 12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [ ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

Challenges arise when configuring routing in angular, nginx, and docker and encountering issues upon

Currently, I have set up angular with nginx as a reverse proxy within a docker container. The issue I am facing is related to the routing of the angular application. While I can smoothly navigate through various pages using the navbar, reloading the page ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Just completed the upgrade of my Angular project from version 9 to version 12, but now encountering issues with a module that utilizes Plotly

Here is the content of my app module file. All components and imports are in their respective places as specified in the documentation: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from &apos ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Trigger a table refresh to display updated information

When I select the select option to make an API call for a new datasource, my table appears before fetching data and it remains empty. Additionally, if I choose another select option, it displays the previous data from the previous selection. I have attemp ...

Angular is used to send an HTTP GET request

I'm seeking assistance with implementing a get and put request in Angular. I understand how to initiate a get or put request when a button is clicked, by binding the request to the button itself. However, I am now looking for a way to trigger a get re ...

Prevent the selection of rows and only enable the option to select checkboxes in PrimeNG's Multiselect feature

I'm currently working on a task that involves using PrimeNG multiselect. This particular multiselect includes checkboxes followed by text within each row. I need to disable the ability to select rows by clicking on the text, and instead only allow sel ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...