html - Angular 2 al hacer clic en la celda de la tabla hacerla editable
Tengo un ngFor para filas y quiero que cuando haga clic en alguna celda sea editable
<tr *ngFor="let invoice of invoiceItem.rows">
<td contenteditable='true' (input)="onRowClick($event, invoice.rowId)">{{ invoice.rowName }}</td>
<td>{{ invoice.hours}}</td>
<td>{{ invoice.price }}</td>
<td>{{ invoice.comments }}</td>
<td>{{ invoice.total}} </td>
</tr>
Además, quiero respaldarlo con nuevas filas añadidas
<button (click)='addRow()'>Add a row</button>
addRow() {
this.invoiceItem.rows.push({
invoiceDetailsId: this.invoiceItem.item.invoiceId,
rowName: '',
hours: 0,
price: 0,
comments: '',
total: 0,
rowId:
})
}
onRowClick(event, id) {
console.log(event.target.outerText, id);
}
¿Qué debería implementar para esta tarea?
Respuesta #1
Aquí hay una solución que funciona. Puede que no sea bonita, pero funciona.
Cambia la estructura de tu tabla a algo como esto:
<tr *ngFor="let invoice of invoiceItem.rows">
<td *ngIf="invoice.rowId == editRowId">
<input type="text" [(ngModel)]="invoice.hours">
</td>
<td *ngIf="invoice.rowId !== editRowId" (click)="toggle(invoice.rowId)">
{{invoice.rowId}}
</td>
<!-- the rest of your fields in same manner -->
</tr>
Y en tu componente:
editRowId: any;
toggle(id){
this.editRowId = id;
}
Esto también admite la adición de una nueva fila. He ideado un truco para establecer el id de la nueva fila, de la siguiente manera:
addRow() {
let indexForId = this.invoiceItem.rows.length + 1
this.rows.push({
// .....
rowId: indexForId,
})
}
Podrías encontrar una mejor manera :)
Aquí hay un plunker que funciona
Respuesta #2
ok, primero agregarás 1 propiedad más para cada invoice llamada editable: false, luego al recorrer la lista, enlazarás los datos así;
[contenteditable]="invoice.editable"
haz esto para todos los td
<td (input)="onRowClick($event, invoice.rowId)">
<div [contenteditable]="invoice.editable ? 'true': 'false'">{{ invoice.rowName }}</div>
</td>
