1

I get this table in angular material

<mat-table [dataSource]="dataSource">
 <ng-container matColumnDef="{{this.columnsToDisplay[3]}}">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>{{this.columnsToDisplay[3]}}</th>
    <td mat-cell *matCellDef="let element; let i=index">
      <mat-form-field class="form-input">
        <input type="number" matInput [(ngModel)]="quincenaUrl==1?element.dia2:element.dia17"
          (keyup.enter)="editarCelda($event)" />
      </mat-form-field>
    </td>
  </ng-container>

....
<tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky:true"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;" class="element-row"></tr>
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell" colspan="4">No se han encontrado coincidencias</td>
  </tr>

</mat-table>

When I edit a value and Press Enter in my class I get the event

editarCelda(event: any) {
 console.log("Nuevo Valor", event.target.value);
}

And I know how to get the value but I don't know how to get the row and column edited, that is, the position of the edited cell

Any idea, please?

Thanks

kintela
  • 1,283
  • 1
  • 14
  • 32

2 Answers2

2

pass the row and column when calling the editarCelda method

<mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="{{this.columnsToDisplay[3]}}">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>
      {{this.columnsToDisplay[3]}}
    </th>
    <td mat-cell *matCellDef="let element; let i=index">
      <mat-form-field class="form-input">
        <input
          type="number"
          matInput
          [(ngModel)]="quincenaUrl==1?element.dia2:element.dia17"
          (keyup.enter)="editarCelda($event, i, this.columnsToDisplay[3])"
        />
      </mat-form-field>
    </td>
  </ng-container>

  ....
  <tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky:true"></tr>
  <tr
    mat-row
    *matRowDef="let element; columns: columnsToDisplay;"
    class="element-row"
  ></tr>
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell" colspan="4">No se han encontrado coincidencias</td>
  </tr>
</mat-table>
editarCelda(event, row, col) {
  ...
}
Mr. Stash
  • 2,940
  • 3
  • 10
  • 24
0
editarCelda(event: any) {
  // Get the value of the edited cell
  const newValue = event.target.value;

  // Get the index of the current row (the edited cell is in this row)
  const rowIndex = event.target.parentElement.parentElement.index;

  // Get the name of the column by using the interpolation in the matColumnDef
  // directive (in this case, the name of the column is the fourth element
  // in the columnsToDisplay array)
  const columnName = this.columnsToDisplay[3];

  console.log(`Row: ${rowIndex}, Column: ${columnName}`);
}
merovingian
  • 515
  • 2
  • 9