角2选择/取消选择所有复选框
问题描述:
我要选择/取消选择所有复选框。我试图闯民宅其他代码,但没有什么工作对我来说角2选择/取消选择所有复选框
下面是我的代码。选择unseleting特定单位正在为我工作。基本上当我点击div它选择/取消选择复选框,并添加颜色。但我很困惑与选择所有/取消选择所有
请帮我用我的代码
//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 {}
答
制作由拉胡尔和ncohen提供意见的组合做我们可以在这里使用patchValue
。
而对于取消选择所有复选框,我把它改成一个按钮,在这个答案,对我来说,似乎是一个复选框是不是真的适合(?),因为处理在复选框中打勾。但是,这取决于你,如果你愿意使用复选框:)
至于检查是否“全选”复选框应进行检查或没有,你可以这样做:
[checked]="checkAllSelected()"
,然后在TS:
checkAllSelected() {
return this.form.controls.unitArr.controls.every(x => x.value == true)
}
这里我们则必须记住,这是在每个变化检测运行。所以也许你会想用一个变量来代替,这当然取决于具体情况,即这对你来说代价如何,但我不认为它会成为这种情况。
因此,这是您的范本看起来怎么样:
<label>
<input type="checkbox" [checked]="checkAllSelected()"
(click)="selectAll($event.target.checked)"/>Select all
</label>
<button (click)="unselectAll($event.target.checked)">Unselect All</button>
我们的复选框的状态模板,evalate传递要么检查所有或取消所有:
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))
}
当然,当用户点击清除按钮:
unselectAll() {
this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}
我猜你正在寻找的东西像[这](https://embed.plnkr.co/h9wFGz/) –
为什么不张贴此作为回答,而不是评论,然后? – Graham
不要这样写:'formControlName = “{{我}}”'但是这不是:'[formControlName] = “我”' – ncohen