这是一个工作版本,复选框逻辑工作正常,希望有帮助!
我们需要使用
获取表单组,但我们还需要访问内部表单控件,然后获取复选框值!control.value
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import {
FormArray,
FormControl,
FormGroup,
ReactiveFormsModule,
} from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { MatCheckboxModule } from '@angular/material/checkbox';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ReactiveFormsModule, MatCheckboxModule],
template: `
<form [formGroup]="form">
<div formArrayName="array">
<div *ngFor="let control of checkboxArray.controls;let i = index" [formGroupName]="i">
<mat-checkbox formControlName="test" style="margin-bottom: 15px;"
(change)="onCheckedChange(i);">
{{ checkboxItems[i].name }}
</mat-checkbox>
</div>
</div>
</form>
`,
})
export class App {
name = 'Angular';
form = new FormGroup({
array: new FormArray([]),
});
lists = [];
checkboxItems: any = [];
ngOnInit() {
this.add();
this.add();
this.add();
}
add() {
this.checkboxArray.push(
new FormGroup({
test: new FormControl(false),
})
);
this.checkboxItems.push({ name: 'test' });
}
get checkboxArray() {
return this.form.get('array') as FormArray;
}
onCheckedChange(index: number) {
// this.sortCheckboxArray();
// const checkboxItem = this.checkboxItems[index];
const control = this.checkboxArray.at(index);
if (control) {
if (control.value.test) {
console.log('checked');
// this.lists.push(checkboxItem.id.toString());
} else {
console.log('not checked');
// this.lists.pop(checkboxItem.id.toString());
}
}
// this.updateSubscriberGroupsCount();
// this.cdr.detectChanges();
}
}
bootstrapApplication(App);