简体   繁体   中英

How to get the edited cell position in Angular material table

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

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) {
  ...
}
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}`);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM