How to update a specific row's value in an Angular table with duplicate data using (change)...

Discussão em 'Angular' iniciado por Dayakar Kodirekka, Dezembro 5, 2024.

  1. I am working on an Angular project where I have a table generated using *ngFor. The table rows represent objects in an array, and the data can have duplicate entries (same name or other properties). Each row has an input field that allows the user to change a specific property (e.g., leverage).

    Here’s an example of my table structure:

    <table>
    <thead>
    <tr>
    <th>Name</th>
    <th>Leverage</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let item of m_backtestedBenchmarks; let i = index">
    <td>{{ item.name }}</td>
    <td>
    <input
    type="text"
    [value]="item.leverage"
    (change)="onLeverageChange($event, i)"
    />
    </td>
    </tr>
    </tbody>
    </table>


    Here’s my TypeScript logic to handle the change:

    onLeverageChange(event: Event, index: number) {
    const newValue = parseFloat((event.target as HTMLInputElement).value.trim());
    if (!isNaN(newValue)) {
    this.m_backtestedBenchmarks[index].leverage = newValue;
    console.log('Updated array:', this.m_backtestedBenchmarks);
    }
    }


    However, my data can have duplicate rows, like this:

    m_backtestedBenchmarks = [
    { name: "Portfolio A", leverage: 1.25 },
    { name: "Portfolio A", leverage: 1.25 }
    ];


    In this scenario, the (change) event sometimes updates both rows instead of just the one the user interacted with. I want to ensure that only the row corresponding to the user’s input is updated, even if the rows share the same data (e.g., duplicate name or other properties)

    My Questions: How can I ensure that only the specific row being edited gets updated when duplicates exist? Is the (change) event with [value] the right approach for this scenario? If not, what would be a better Angular-idiomatic way? Are there any best practices or considerations for handling updates to arrays with duplicate objects in Angular? Any guidance or examples would be greatly appreciated!

    Continue reading...

Compartilhe esta Página