角度2复选框以选择全部

时间:2016-09-18 16:48:02

标签: javascript html angular typescript

问题

我找到了这个问题的答案,但我仍然坚持我有一个多行的表,每行有一个复选框,我需要一个复选框来选择所有并取消全部,这里有一些示例代码

模板

<table class="table table-bordered table-condensed table-striped table-hover">
<thead>
    <tr>
        <th></th>
        <th>Size</th>
        <th>Diameter</th>
        <th class="text-center">
            <input type="checkbox" name="all" (change)="checkAll($event)"/>
        </th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let size of sizes | async ; let i = index">
        <td class="text-right">{{i + 1}}</td>
        <td class="text-right">{{size.size}}</td>
        <td>{{size.diameter}}</td>
        <td class="text-center">
            <input type="checkbox" name="sizecb[]" value="{{size.id}}"/>
        </td>
    </tr>
</tbody>

组件

    export class ListSizeComponent implements OnInit {
    constructor () {
    }

    sizes: any;

    setSizes() {
        this.sizes = [
            {'size': '0', 'diameter': '16000 km'},
            {'size': '1', 'diameter': '32000 km'}
        ]
    }

    checkAll(ev) {
        if (ev.target.checked) {
            console.log("True")
        } else {
            console.log("False");
        }
    }

    ngOnInit(): void {
        this.setSizes();
    }
}

8 个答案:

答案 0 :(得分:17)

您可以利用ngModel来做到这一点。

<强>模板

<input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
....
<input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state"/>

<强>组件

checkAll(ev) {
  this.sizes.forEach(x => x.state = ev.target.checked)
}

isAllChecked() {
  return this.sizes.every(_ => _.state);
}

<强> Stackblitz Example

答案 1 :(得分:8)

这可以 >使用 [(ngModel)] 来完成!

在组件'ListSizeComponent'中声明并初始化一个布尔变量'isSelected'为false。 并且,将[Checked] =“isSelected”属性添加到所有复选框。并且,添加“全部”复选框的以下更改事件。 (更改)=“​​isSelected = true”。

所以你的代码如下所示,

<table class="table table-bordered table-condensed table-striped table-hover">
<thead>
    <tr>
        <th></th>
        <th>Size</th>
        <th>Diameter</th>
        <th class="text-center">
            <input type="checkbox" name="all" (change)="isSelected = true"/>
        </th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let size of sizes | async ; let i = index">
        <td class="text-right">{{i + 1}}</td>
        <td class="text-right">{{size.size}}</td>
        <td>{{size.diameter}}</td>
        <td class="text-center">
            <input type="checkbox" name="sizecb[]" value="{{size.id}}" 
             [checked]="isSelected"/>
        </td>
    </tr>
</tbody>
</table>

成分:

export class ListSizeComponent implements OnInit {
constructor () {
}

sizes: any;
isSelected = false;

setSizes() {
    this.sizes = [
        {'size': '0', 'diameter': '16000 km'},
        {'size': '1', 'diameter': '32000 km'}
    ]
}



ngOnInit(): void {
    this.setSizes();
}

答案 2 :(得分:6)

在HTML文件中:

选中所有复选框:

<div class="col-sm-6" *ngFor="let feature of features">
 <input type="checkbox" [checked]="isSelected"> {{feature.text}}
</div>

对于要选择的复选框列表:

df1<-data.frame(group = c("A","A","A","A","B","B","B","B","C","C","C","C"),index=c(1,2,3,4,5,6,7,8,9,10,11,12),start=c(5,10,15,20,5,10,15,20,5,10,15,20),end=c(10,15,20,25,10,15,20,25,10,15,20,25))
df2<-data.frame(group = c("A","B","B","C","A","C"),time=c(11,17,24,5,5,22))
df3<-data.frame(time=c(11,17,24,5,5,22),index=c(2,7,8,9,1,12))

答案 3 :(得分:0)

执行全选复选框的示例代码。

<li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/>
          </li>
          <li *ngFor="let n of names"> 
          <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">
          {{n.name}}
     </li>

.....

selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }

For more info

答案 4 :(得分:0)

这是一种更现代的方法,无需SoapClient或外部跟踪所选项目。纯ngModel方法:

MatSelectionList

答案 5 :(得分:0)

正确答案非常简单(基本上重复Syed Muhammad Abid的答案)。

TS:

multiSelect: boolean = true;

HTML:

<table>
    <tr>
        <th><input type="checkbox" [checked]="multiSelect" (change)="multiSelect = !multiSelect"/></th>
        <th>Value</th>
   </tr>
   <tr *ngFor="let item of items">
       <td><input type="checkbox" [checked]="multiSelect" /></td>
       <td>{{item.value}}</td>
   </tr>
</table>

答案 6 :(得分:0)

zone1 = [
    { name: 'Capot avant', checked: false },
    { name: 'Pare-chocs avant', checked: false }
  ]

get selectedZone1() {enter code here
    return this.zone1.filter(item => item.checked).map(item => item.name)
  }


        <!-- zone 1 -->
  <ul>
    <h3 class="titre font-weight-bold zone"><b>ZONE 1</b></h3>
    <li *ngFor="let item of zone1">
      <mat-checkbox [(ngModel)]="item.checked">
        {{item.name}}
      </mat-checkbox>
    </li>
  </ul>

答案 7 :(得分:-1)

它不起作用,我认为这是因为在我的真实代码中,通过对服务的异步调用获得“大小”,我得到了这个错误:

this.sizes.every不是函数

我的意思是组件中的尺寸是一个Observable对象

我必须纠正我的答案以澄清我的情况,我有一个服务,我以这种方式获得数组大小:

getSizes () {

    let sizesUrl = 'http://localhost:8000/sizes';

    return this.http.get(sizesUrl).map(this.extractData)
}

private extractData(res: Response) {
    let body = res.json();
    //console.log(body);
    let sizes: Size[] = new Array();
    for (let x = 0; x < body['hydra:member'].length; x++) {
        let size = new Size;
        let item = body['hydra:member'][x];
        size.id = item['@id'].substring(item['@id'].length - 1);
        size.size = item['size'];
        size.diameter = item['diameter'];
        size.example = item['example'];
        size.surfaceGravity = item['surfaceGravity'];
        sizes.push(size);
    }
    return sizes || { };
}

所以在组件中,sizes是一个Observable,所以如果我调用subscribe:

arr: any[];
sizes: any;

setSizes() {
    this.sizes = this.sizeService
        .getSizes()
        .subscribe(data => {
            this.arr = data;
        });
}

checkAll(ev) {
    if(!this.arr) return;
    this.arr.forEach(x => x.state = ev.target.checked)
}

isAllChecked() {
    if(!this.arr) return;
    return this.arr.every(_ => _.state);
}

ngOnInit(): void {
    this.setSizes();
}

我遇到编译错误“类型'{}'不能分配给任何[]”类型,而大小不是更多的Observable对象,但它是一个订阅者对象,我不能在异步管道中使用它。 对于所有这些混乱,我感到很遗憾,我担心我被困在一条没有出路的隧道里。

无论如何,谢谢你的回答:)