使用Angular编辑并保存表中的行

问题描述 投票:1回答:1

在Angular中,如何在不使用ag-grid或任何其他内置表库的情况下创建html表。

[我正在寻找一个简单的html表的示例,可以在其中编辑任何行中的任何列,然后有一个保存按钮,仅保存Edited cell/row。这也将帮助我解决上一个问题Angular edit row & store values in array

javascript angularjs angular typescript angular5
1个回答
0
投票

使用标准网格总是更好,但是如果您要编辑HTML表,可以对td使用contenteditable =“ true”使其可编辑,并在模糊时手动更新对象。请在下面找到完整的代码

HTML

<table border="1" width="50%">
      <thead>
            <tr>
                  <td>First Name</td>
                  <td>Second Name</td>
            </tr>
      </thead>
      <tbody>
            <tr *ngFor="let item of data; let indx = index">
                  <td contenteditable="true" width="50%" (blur)="setData($event,'firstName',indx)">
                        {{ item.firstName }}
                  </td>
                  <td contenteditable="true" width="50%" (blur)="setData($event,'secondName',indx)">
                        {{ item.secondName }}
                  </td>
            </tr>
      </tbody>
</table>

保存

TS文件

import { Component, OnInit } from "@angular/core";
@Component({
  templateUrl: "./event.detail.component.html"
})
export class EventDetailComponent implements OnInit {
  data = [];
  constructor() {}
  ngOnInit() {
    this.data = [
      { firstName: "Some First", secondName: "Some Secons" },
      { firstName: "Some First", secondName: "Some Secons" },
      { firstName: "Some First", secondName: "Some Secons" },
      { firstName: "Some First", secondName: "Some Secons" }
    ];
  }
  public saveDate() {
    console.log(this.data);
  }
  public setData(event, key, indx) {
    this.data[indx][key] = event.target.innerText;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.