将表格单元格转换为可编辑输入

时间:2018-10-11 07:34:47

标签: html angular6

我想创建一个包含2列的表格:NameEmail。每次按下edit button时,我都想将td转换成可编辑的输入。问题是,如果我有更多用户,然后按“编辑”按钮,则所有用户都将变为可编辑状态,而不仅是所选用户。我该如何解决这个问题?

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of usersList">
      <td *ngIf="!editUser">{{ user.name }}</td>
      <td *ngIf="editUser"><input class=" form-control" size="1" type="text" [(ngModel)]="user.name"></td>

      <td *ngIf="!editUser">{{ user.email }}
      <td *ngIf="editUser"><input class=" form-control" size="1" type="text" [(ngModel)]="user.email"></td>

      <td *ngIf="!editUser">
        <a class="action-btn" (click)="onEdit()">
          <p class="material-icons pointer">edit</p>
        </a>
      </td>
    </tr>
  </tbody>
</table>

editUser: boolean = false
onEdit() {
  this.editUser = !this.editUser
}

按下红色按钮之前表格的外观 How the table looks before pressing the red button

按下按钮后表格的外观 How the table looks after pressing the button

感谢您的宝贵时间! (this is what I want to achieve

2 个答案:

答案 0 :(得分:1)

您有该用户的ID吗?

然后您可以执行以下操作:

<tbody>
  <tr *ngFor="let user of usersList">
    <td *ngIf="editUserId !== user.id">{{ user.name }}</td>
    <td *ngIf="editUserId === user.id"><input [(ngModel)]="user.name"></td>

    <td *ngIf="editUserId !== user.id">{{ user.email }}
    <td *ngIf="editUserId === user.id"><input [(ngModel)]="user.email"></td>

    <td *ngIf="editUser !== user.id">
      <a class="action-btn" (click)="onEdit(user.id)">
        <p class="material-icons pointer">edit</p>
      </a>
    </td>
  </tr>
</tbody>

editUserId: number;
onEdit(userId: number) {
  this.editUserId = userId;
}

答案 1 :(得分:0)

尝试一下,它将为您服务。

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of usersList; index as i">
      <td *ngIf="i!=selectedRowIndex">{{ user.name }}</td>
      <td *ngIf="selectedRowIndex == i"><input class=" form-control" size="1" 
        type="text" [(ngModel)]="user.name"></td>
          <td *ngIf="i!=selectedRowIndex">{{ user.email }}
      <td *ngIf="selectedRowIndex == i"><input class=" form-control" size="1" 
               type="text" [(ngModel)]="user.email"></td>
          <td>
        <a class="action-btn" (click)="onEdit(i)">
          <p class="material-icons pointer">edit</p>
        </a>
      </td>
    </tr>
  </tbody>
</table>

selectedRowIndex = -1
onEdit(rowIndex) {
  this.selectedRowIndex = rowIndex;
}
相关问题