Javascript 角度 2 复选框以全选

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39560199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:41:29  来源:igfitidea点击:

angular 2 checkbox to select all

javascripthtmlangulartypescript

提问by Lupo Wolfman Solitario

Problem

问题

I looked for answers to this problem but I'm still stuck I have a table with multiple rows with a checkbox on every row, I need a checkbox to select all and deselect all, here some example code

我寻找了这个问题的答案,但我仍然卡住我有一个多行的表格,每一行都有一个复选框,我需要一个复选框来全选和取消全选,这里有一些示例代码

Template

模板

<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>

Component

成分

    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();
    }
}

回答by yurzui

You can leverage ngModelto do that.

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

Template:

模板

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

Component:

组件

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

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

Stackblitz Example

Stackblitz 示例

回答by Amey P Naik

This can be done withoutusing [(ngModel)]also !

这也可以在使用[(ngModel)] 的情况下完成!

Just declare and initialize a boolean variable 'isSelected' to false in the component 'ListSizeComponent '. And, add [Checked] = "isSelected" property to all the checkboxes. And, add the following change event of the 'all' checkbox. (change)="isSelected = true".

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

So your code looks like below,

所以你的代码如下所示,

<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>

component:

成分:

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();
}

回答by Syed Muhammad Abid

In HTML file:

在 HTML 文件中:

Select all check box:

全选复选框:

<div class="col-sm-6">
<input type="checkbox" (change)="isSelected = !isSelected"> Select all
</div>

For List of checkboxes to be selected:

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

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

回答by Prashobh

Example code for doing select all checkbox.

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

<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

欲了解更多信息

回答by ZBAGI

Here is more modern approach without ngModelor external tracking of selected items. Pure MatSelectionListapproach:

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

public toggle(list: MatSelectionList) {
    if (this.isAllChecked(list)) {
        list.deselectAll();
    } else {
        list.selectAll();
    }
}

public isAllChecked(list: MatSelectionList): boolean {
    // Make sure list exists
    if (!list.options)
        return false;
    return list.options.toArray().every(o => o.selected);
}

回答by schlock

The correct answer is pretty simple (basically repeating Syed Muhammad Abid's answer).

正确答案非常简单(基本上是重复赛义德·穆罕默德·阿比德的答案)。

TS:

TS:

multiSelect: boolean = true;

HTML:

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>

回答by Lupo Wolfman Solitario

It doesn't work, I think it is because in my real code I get "sizes" by an async call to http.get trough a services and I got this error:

它不起作用,我认为这是因为在我的真实代码中,我通过对 http.get 服务的异步调用获得了“大小”,并且出现了以下错误:

this.sizes.every is not a function

this.sizes.every 不是函数

I mean sizes in the component is an Observable object

我的意思是组件中的大小是一个 Observable 对象

I have to correct my answer to clarify my situation, i have a service where I get the array sizes in this way:

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

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 || { };
}

so in the component, sizes is an Observable, so if I call subscribe:

所以在组件中,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();
}

I got a compile error "Type '{}' is not assignable to type any[]", and sizes is not more an Observable object but it's a Subscriber object and I can't use it in the async pipe. I'm sorry for all this confusion, I'm afraid that I was stuck in a tunnel with no way out.

我收到一个编译错误“类型 '{}' 不可分配给类型 any[]”,并且大小不是一个 Observable 对象,而是一个 Subscriber 对象,我不能在异步管道中使用它。我很抱歉所有这些混乱,我担心我被困在没有出路的隧道中。

thanks anyway for your answer :)

无论如何感谢您的回答:)