选中/取消选中 mat-checkbox 未正确返回 true 或 false

问题描述 投票:0回答:1
angular angular-material
1个回答
0
投票

这是一个工作版本,复选框逻辑工作正常,希望有帮助!

我们需要使用

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

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.