首页 > 解决方案 > 如何动态地将 id 添加到表行中,以便可以唯一标识它们

问题描述

我在 manage.component.html 中有一个表结构,其中填充了来自服务器的数据。我有一个“编辑”按钮,可用于编辑列中的单元格。

要求:我想唯一标识每个单元格,可以进一步用于编辑并将值返回值发送回服务器以进行更新。

我试图将“counter”附加到“id”的“id”上,这样可以用来唯一标识每个行单元格,但是“counter”没有设置在“id”上

管理.component.html

<tbody>
          <tr *ngFor="let work of workflows$">
            <td>{{work.req_id}}</td>
            <td><input id="btnn{{count$}}" type="text" value="{{work.client_ip}}" maxlength="4" placeholder="name" onload="addID()"/></td>
            <td>{{work.client_type}}</td>
            <td>{{work.project}}</td>
            <td><button (click)="edit()" type="button" class="btn btn-primary">Edit</button></td>
          </tr>
</tbody>

管理.component.ts

export class ManageComponent implements OnInit {

count$ = 0;

edit(event){
    document.getElementById('btnn').focus();
  }

addID(){
    this.count$ = 5;
  }
}

当我单击“编辑”按钮时,焦点应该在行的元素上,编辑后,当我单击“发送”按钮时,值的更改应该可以在 .ts 文件上访问,以便可以将值发送回服务器。

标签: javascriptangular6

解决方案


有多种方法可以做到这一点。但是由于您想通过 id 或 class 获取它,请查看以下代码

<tbody>
          <tr *ngFor="let work of workflows$; let i = index">
            <td>{{work.req_id}}</td>
            <td><input id="btnn-{{i}}" type="text" value="{{work.client_ip}}" maxlength="4" placeholder="name" onload="addID(i)"/></td>
            <td>{{work.client_type}}</td>
            <td>{{work.project}}</td>
            <td>

            <!-- Pass the index i as a parameter in edit() method -->
            <button (click)="edit(i)" type="button" class="btn btn-primary">Edit</button>

            </td>
          </tr>
</tbody>

在你的打字稿中

edit(_index){
    document.getElementById('btnn-'+_index).focus(); //get the element by id
  }

希望有帮助


推荐阅读