Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 on click table cell make it editable

I have a ngFor for rows and I what when i click on some cell to make it 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>

more over I what to support it with new rows added

<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);
    }

what should i implement for this task?

like image 519
shaharnakash Avatar asked Feb 06 '23 04:02

shaharnakash


1 Answers

Here's one solution that works. It might not be pretty, but it works.

Change your table structure to something like this:

<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>

And in your component:

editRowId: any;

toggle(id){
  this.editRowId = id;
}

This also supports the adding of a new row. I have come up with a hack for setting the id for the new row, like so:

addRow() {
  let indexForId = this.invoiceItem.rows.length + 1
  this.rows.push({
    // .....
    rowId: indexForId,
  })
}

You might find a better way :)

Here's a working plunker

like image 184
AT82 Avatar answered Feb 07 '23 17:02

AT82