微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐