如何在角度为7

时间:2019-09-19 17:58:23

标签: html angular typescript

我有一个表的数据来自循环。在这里,当您按下添加按钮时,新的类似行将被添加在底部。再次当您按下编辑按钮时,所有文本框将被启用(最初禁用)。但是,当我选中单个复选框或多个复选框并按Delete按钮时,基于选中复选框的所有行都将被删除/删除。同样,当我单击Delete按钮而不选择任何复选框时,警告消息也应显示,并且当用户选中所有复选框时,试图删除所有行,警告消息应该在那儿,``至少应该有一行'',除非取消选中任何一行,否则他不能删除所有行。我是新来的有人可以帮助我。 https://stackblitz.com/edit/angular-wscsmy

下面的代码

app.component.html

<div class="container">
    <h2>Basic Table</h2>
    <p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
    <div><button (click)="enable()">Edit</button> &nbsp;
    <button (click)="delete()">Delete</button> </div>
    <table class="table border">

        <tbody>
            <tr *ngFor="let row of groups;let i = index" (click)="setClickedRow(i)"  [class.active]="i == selectedRow">
              <td> <input type="checkbox"></td>
                <td> <input #focus [disabled]='toggleButton' type="text" value="{{row.name}}"> </td>
                <td> <input [disabled]='toggleButton' type="text" value="{{row.items}}"> </td>
                <td> <button (click)="addRow(i)">Add</button></td>
            </tr>
        </tbody>
    </table>
</div>

app.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  selectedRow: Number;

  @ViewChild('focus', { static: false }) input: ElementRef;
  public toggleButton: boolean = true;
  ngOnInit() {

  }
  groups = [
    {
      "name": "pencils",
      "items": "red pencil"
    },
    {
      "name": "rubbers",
      "items": "big rubber"
    },
    {
      "name": "rubbers1",
      "items": "big rubber1"
    },
  ];
  addRow(index): void {
    var currentElement = this.groups[index];
    this.groups.splice(index, 0, currentElement);
  }
  enable() {
    this.toggleButton = false
    setTimeout(() => { // this will make the execution after the above boolean has changed
      this.input.nativeElement.focus();
      this.selectedRow = 0;
    }, 0);
  }
  delete(){
    alert('hello');
  }
  setClickedRow(index) {
    this.selectedRow = index;
  }
}

2 个答案:

答案 0 :(得分:0)

您必须创建一个数组来跟踪每个复选框的状态。并在每次选中或取消选中复选框时进行更新。

模板:

<td>
  <input type="checkbox" (click)="toggleSelection($event, i)" [checked]="checkboxes[i]">
</td>

组件:

checkboxes: boolean[];

ngOnInit() {
   this.checkboxes = new Array(this.groups.length);
   this.checkboxes.fill(false);
}

toggleSelection(event, i) {
  this.checkboxes[i] = event.target.checked;
}

此外,每当添加新行时,将另一个复选框条目添加到数组。

addRow(index): void {
  // Other code.
  this.checkboxes.splice(index, 0, false);
}

您可以使用Array.splice()从数组中删除元素。

Array.some()可用于检查是否至少选中了一个复选框,而Array.every()可用于检查是否选中了所有复选框。

delete() {
  var atleastOneSelected = this.checkboxes.some(checkbox => checkbox === true);
  var allSelected = this.checkboxes.every(checkbox => checkbox === true);

  if (!atleastOneSelected) {
    alert("No rows selected.");
    return;
  }

  if (allSelected) {
    alert("At least one row should be present.");
    return;
  }

  // Iterating in reverse to avoid index conflicts by in-place deletion.
  for (let i = this.checkboxes.length-1; i >= 0; i--) {
    // If selected, then delete that row.
    if (this.checkboxes[i]) {
      this.groups.splice(i, 1);
    }
  }

  // Remove entries from checkboxes array.
  this.checkboxes = this.checkboxes.filter(checkbox => checkbox === false);
}

StackBlitz上的实时演示:https://stackblitz.com/edit/angular-abhkyk

答案 1 :(得分:0)

使用一个辅助数组,在其中存储所有选中的复选框。删除之前,请检查至少有一个值。

我选择将项目的索引存储到helper数组,然后基于该索引从原始数组中删除。所以也许是这样的:

toBeDeleted = [];

// called when button is clicked
delete() {
  if (!this.toBeDeleted.length) {
    alert('Choose at least one!');
  } else if (this.toBeDeleted.length === this.groups.length) {
      alert('You cannot delete all rows')
  } 
  else {
    this.groups = this.groups.filter((currentValue, index, arr) => !this.toBeDeleted.includes(index));
  }
  // reset the array
  this.toBeDeleted = [];
}


remove(event, index) {
  // check if checkbox is checked, if so, push to array, else delete from array
  if (event.target.checked) {
    this.toBeDeleted.push(index)
  } else {
    const idx = this.toBeDeleted.indexOf(index);
    this.toBeDeleted.splice(idx, 1)
  }
}

然后在模板中,当用户单击复选框时,调用remove()并传递$event和项目索引:

 <td> <input type="checkbox" (click)="remove($event, i)"></td>

STACKBLITZ