如何在Angular2中的某个按钮单击中在表格中上下移动行?

时间:2017-10-13 06:15:12

标签: html-table angular2-template angular2-forms angular2-directives

下面是我的html表的代码,我需要在上面添加一个函数 点击按钮可以向上或向下移动行?

 <table class="table table-striped">
            <thead class="thead">
                <tr>
                    <th>Name</th>
                    <th>Key</th>
                    <th>Token</th>
                    <th>Color</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let value of values">
                    <td>
                        {{value.name}}
                    </td>
                    <td>
                        {{value.key}}
                    </td>
                    <td>
                        {{value.token}}
                    </td>
                    <td>
                        {{value.color}}
                    </td>
                    <td>
                        <button class="btn btn-success" (click)="editvalue(value);">edit</button> |

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

你能帮帮我怎么做?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

可以轻松地更新数据项索引,如下所示。

<强> HTML

 <table class="table table-striped">
            <thead class="thead">
                <tr>
                    <th>Name</th>
                    <th>Key</th>
                    <th>Token</th>
                    <th>Color</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let value of values; let index = index;">
                    <td>
                        {{value.name}}
                    </td>
                    <td>
                        {{value.key}}
                    </td>
                    <td>
                        {{value.token}}
                    </td>
                    <td>
                        {{value.color}}
                    </td>
                    <td>
                        <button class="btn btn-success" (click)="moveUp(value, index);">Move Up</button>
                    </td>

                    <td>
                        <button class="btn btn-success" (click)="moveDown(value, index);">Move Down</button>
                    </td>
                </tr>
            </tbody>
        </table>

<强> Component.ts

moveUp(value, index) {
    if (index > 0) {
      const tmp = this.values[index - 1];
      this.values[index - 1] = this.values[index];
      this.values[index] = tmp;
    }
  }

 moveDown(value, index) {
        if (index < this.values.length) {
          const tmp = this.values[index + 1];
          this.values[index + 1] = this.values[index];
          this.values[index] = tmp;
        }
      }