html – 单击表格单元格上的Angular 2使其可编辑

我有一个ngFor for rows和我点击某些单元格以使其可编辑

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

更多的是我添加了新行来支持

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

我应该为这项任务实施什么?

解决方法

这是一个有效的解决方案.它可能不漂亮,但它的工作原理.

将表结构更改为以下内容

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

在您的组件中:

editRowId: any;

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

这也支持添加新行.我想出了一个用于为新行设置id的hack,如下所示:

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

你可能会找到一个更好的方法:)

这是一个工作plunker

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些