shaharnakash
shaharnakash

Reputation: 675

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?

Upvotes: 5

Views: 24142

Answers (2)

AVJT82
AVJT82

Reputation: 73357

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

Upvotes: 8

Tiep Phan
Tiep Phan

Reputation: 12596

ok, first you will add 1 more property for each invoice called editable: false, then when looping through list, you'll binding data like this;

[contenteditable]="invoice.editable"

do this for all td

<td (input)="onRowClick($event, invoice.rowId)">
    <div [contenteditable]="invoice.editable ? 'true': 'false'">{{ invoice.rowName }}</div>
</td>

Upvotes: 0

Related Questions