如果我在 mat-dialog 中单击取消提交按钮,如何取消选中 mat-checkbox

问题描述 投票:0回答:2

我编写了一个对话框,其中包含要从表中删除的所有选定行。现在,当我提交对话框时,我希望也取消选中激活的复选框。

解决这个问题的最佳方法是什么?

我的代码:

// HTML

<mat-checkbox (click)="toggleCheckboxes()"></mat-checkbox>

// TS

private all = false;

public toggleCheckboxes() {
    this.all = !this.all;
    for (const formGroup of this.rows.controls) {
      formGroup.get('select').setValue(this.all);
    }
  }

deleteAllSelectedRows() {
if (rowsToRemove.length === formArray.length) {
        const dialogRef = this.dialog.open(DeleteAllRowsComponent, {
          width: '500px',
        });
        const subAllRows = dialogRef.componentInstance.deleteAllRowsAction.subscribe((data: any) => {
          let toDelete = formArray.value.length;
          let deleted = 0;
          const deleteRowCallback = () => {
            deleted += 1;
            if (deleted === toDelete) {
              console.log('All rows finished!');
              dialogRef.close();
              this.refresh();
            }
          };
          for (const value of formArray.value) {
            this.deleteRowBackendData(value, deleteRowCallback);
          }
        });
        dialogRef.afterClosed().subscribe((result) => {
          console.log(`Delete all rows dialog will be closed!`);
          subAllRows.unsubscribe();
        });
      }
}
angular typescript angular-material angular-reactive-forms
2个回答
0
投票

如果您想选择/取消选择所有复选框,请使用按钮?

也许

ngModel

<mat-checkbox [(ngModel)]="all" (click)="toggleCheckboxes()"></mat-checkbox>

public all = false;

public toggleCheckboxes() {
    this.all = !this.all;
    for (const formGroup of this.rows.controls) {
      formGroup.get('select').setValue(this.all);
    }
  }

或者如果您将 ReactiveForm 与

patchValue

一起使用
  cleanForm(): void {
    this.reactiveForm.patchValue({
      checkbox: false
    });
    // or 
    this.reactiveForm.reset();
  }

<mat-checkbox formControlName="checkbox" (click)="toggleCheckboxes()"></mat-checkbox>

0
投票

ReactiveForm 方法有效

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-checkbox-example',
  template: `
    <form [formGroup]="form">
      <mat-checkbox formControlName="isChecked">Check me!</mat-checkbox>
    </form>
  `,
})
export class CheckboxExample {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      isChecked: [false]
    });

    this.form.get('isChecked').valueChanges.subscribe(value => {
      if (!this.condition) {
        this.form.get('isChecked').setValue(false, { emitEvent: false });
      }
    });
  }
}

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