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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42050087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:20:41  来源:igfitidea点击:

Angular 2 on click table cell make it editable

htmlangulartypescript

提问by shaharnakash

I have a ngFor for rows and I what when i click on some cell to make it editable

我有一个 ngFor 行,当我点击某个单元格使其可编辑时我会做什么

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

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

回答by AJT82

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:

这也支持添加新行。我想出了一个为新行设置 id 的技巧,如下所示:

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

You might find a better way :)

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

Here's a working plunker

这是一个工作的plunker

回答by Tiep Phan

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

好的,首先您将为每个invoice被调用的属性添加 1 个属性editable: false,然后在循环遍历列表时,您将像这样绑定数据;

[contenteditable]="invoice.editable"

do this for all td

为所有人做这件事 td

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