我想选择/取消选择所有复选框。我尝试引用其他代码,但对我没有任何帮助
下面是我的代码。选择取消选择特定单元对我有用。基本上,当我点击 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 {}
最佳答案
结合 Rahul 和 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>
我们将复选框的状态传递给模板并评估是选中所有还是取消选中所有:
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))
}
关于Angular 2 选择/取消选择所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594398/