我在Angular 15Angular Material 14中工作,下面是我用来显示复选框列表的HTML代码

<div *ngFor="let control of checkboxArray.controls;let i = index" >
    <mat-checkbox [formControl]="control" (input)="validateInputs(notificationForm)" [checked]="control.value" (change)="control.checked=$event.checked;onCheckedChange(i);">
        {{ checkboxItems[i].name }}
    </mat-checkbox>
</div>

下面是Angular中onCheckedChange个函数的代码

onCheckedChange(index: number) {
    this.sortCheckboxArray();
    const checkboxItem = this.checkboxItems[index];
    const control = this.checkboxArray.at(index);

    if (control) {
      if (control.value) {
        this.lists.push(checkboxItem.id.toString());
      } else {
        this.lists.pop(checkboxItem.id.toString());
      }
    }
    this.updateSubscriberGroupsCount();
    this.cdr.detectChanges();
}

加载CheckBoxlist控件时,大多数控件的名称将消失,如下所示...

当我选中复选框时,在这个onCheckedChange函数中,Control.Value总是返回FALSE.哪里出了问题?我不明白..

EDIT

以下是我之前为addCheckbox函数编写的代码

addCheckbox(id: number, name: string, checked: boolean) {
    const control = new FormControl(false);
    this.checkboxArray.push(control);

    const checkboxItem: SubscribersNotification = { id:id, name:name, checked: false };
    this.checkboxItems.push(checkboxItem);
}

使用此复选框可正确加载控件.但选中/取消选中复选框控件不起作用.

如何修改此代码,使其正确侦听选中/取消选中...

Checkboxes

推荐答案

这是一个工作版本,复选框逻辑运行得很好,希望它能有所帮助!

我们需要使用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);

stackblitz

Angular相关问答推荐

Angular 和PrimeNg文件Uploader:渲染元件时如何显示选定文件的列表?

如何在Angular 17 SSR中处理Swiper 11 Web组件事件

由于ngcc操作失败,Angular扩展可能无法正常工作

Angular ngSubmit 不起作用(内部按钮和导入模块)

Angular6:RxJS switchMap 运算符未按预期工作

导入 AngularFirestoreModule 时出现问题:此类型参数可能需要 `extends firebase.firestore.DocumentData` 约束.

如何在Angular中自动路由到子路由

as和let之间的异步管道区别

react表单上的自定义验证器用于密码并确认密码匹配将未定义的参数导入 Angular 4

Angular 5 中服务的生命周期是什么

由于时区,Angular 4 日期管道显示错误的日期 - 如何解决这个问题?

设置 Angular Material Tooltip 的字体大小

Angular 2 单元测试 - @ViewChild 未定义

ERROR 错误:StaticInjectorError(AppModule)[UserformService -> HttpClient]:

ngx-toastr,Toast 未在 Angular 7 中显示

Angular 2 Material - 如何居中进度微调器

Angular 2 应用程序中没有Access-Control-Allow-Origin标头

RxJS - 发生错误时观察到的不会完成

将 [NgStyle] 与条件组合(if..else)

如何升级 Angular CLI 项目?