Angular 2选择/取消选择所有复选框 [英] Angular 2 Select/unselect all checkbox

查看:76
本文介绍了Angular 2选择/取消选择所有复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要选择/取消选择所有复选框.我尝试引用其他代码,但对我没有任何帮助

i want to select/unselect all checkbox. i tried refering other code but nothing worked for me

下面是我的代码.选择不放弃的特定单位对我有用.基本上,当我单击div时,它会选中/取消选中复选框并为其添加颜色.但我对全选/取消全选感到困惑

below is my code. selecting unseleting particular unit is working for me. basically when i clicks on div it selects/unselects checkbox and adds color to it. but i am confused with select all/unselect all

请帮助我使用我的代码

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { ReactiveFormsModule, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">
    <div formArrayName="unitArr">
    <label><input type="checkbox" />Select all</label>
    <label><input type="checkbox" />unSelect all</label>
      <div 
        *ngFor="let unit of units; let i = index"
        class="unit"
        (click)="onClick(i)"
        [ngClass]="{'unit-selected': unitArr.controls[i].value}">
          <input type="checkbox" formControlName="{{i}}"/>
          <div class="unit-number">{{ unit.num }}</div>
          <div class="unit-desc">{{ unit.desc }}</div>
      </div>
    </div>
  </form>
  `,
  styles: [`.unit-selected { color: red; }`]
})
export class App implements OnInit{
  private units = [
    {num: 1, desc: 'Decription'},
    {num: 2, desc: 'Decription'},
    {num: 3, desc: 'Decription'},
  ];
  private form: Form;
  
  constructor (private fb: FormBuilder) {}
  
  ngOnInit () {
    this.form = this.fb.group({
      unitArr: this.fb.array(
        this.units.map((unit) => {
          return this.fb.control(false); // Set all initial values to false
        })
      )
    });
  }
  
  // Shorten for the template
  get unitArr (): FormArray {
    return this.form.get('unitArr') as FormArray;
  }

  onClick(i) {
    const control = this.unitArr.controls[i];
    control.setValue(!control.value); // Toggle checked
  }
}

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

推荐答案

结合使用 Rahul ncohen 提供的注释,我们可以在此处使用patchValue.

Making a combination of the comments provided by Rahul and ncohen we can use patchValue here.

至于取消选中所有复选框,我在此答案中将其更改为按钮,对我而言,由于处理复选框中的勾号,似乎该复选框并不十分合适(?).但这取决于您是否愿意使用复选框:)

As for the unselecting all checkboxes, I changed it to a button in this answer, to me it seemed that a checkbox wasn't really suitable (?) because of handling the tick in the checkbox. But that is up to you if you rather use a checkbox :)

关于检查是否应选中全选"复选框,您可以执行以下操作:

As for checking if the "Select All" checkbox should be checked or not, you can do:

[checked]="checkAllSelected()"

,然后在TS中:

checkAllSelected() {
  return this.form.controls.unitArr.controls.every(x => x.value == true)
}

然后我们必须记住,此操作在每次更改检测时都运行.因此,也许您想改用一个变量,这当然取决于情况,即这对您而言会造成多大的损失,但我认为在这种情况下不会如此.

Here we then must remember that this is run on each change detection. So perhaps you'd want to use a variable instead, that is of course depending on the case, i.e how costly this would be for you, but I don't think it would be in this case.

这就是您的模板的样子:

So this is how your template could look like:

<label>
   <input type="checkbox" [checked]="checkAllSelected()" 
         (click)="selectAll($event.target.checked)"/>Select all
</label>
<button (click)="unselectAll($event.target.checked)">Unselect All</button>

我们将复选框的状态传递给模板,然后跳过以选中全部或取消全部:

where we pass the status of the checkbox to template and evalate to either check all or uncheck all:

selectAll(isChecked) {
  if isChecked 
     this.form.controls.unitArr.controls.map(x => x.patchValue(true))
  else
     this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

当然,当用户单击取消选中按钮时:

And of course when user clicks the uncheck button:

unselectAll() {
  this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

演示: http://plnkr.co/edit/O194WEimjf3XzfiIrWF0?p =预览

这篇关于Angular 2选择/取消选择所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆