首页 > 解决方案 > mat-checkbox 无法正确显示选中的值

问题描述

我正在使用 Angular Material 的 mat-checkbox 组件。但是当我选中复选框时,如果我引用event.target.querySelector('input[type=checkbox"]').checked,它会告诉我值为 false,当我取消选中复选框时,它会告诉我值为 true。它应该是相反的。

此外,如果我尝试ViewChild与 mat-checkbox 一起使用,它会产生未定义。因此,我无法使用this.el.nativeElement.

我用这个孤立的 git repo 说明了这个问题:

https://github.com/lovefamilychildrenhappiness/AngularMaterialDefaultStyle/commit/4ab86c34adf9ee966981e7ca6afe14ca403fb9c1

以下是 repo 中的一些相关代码:

// app.component.ts
@ViewChild('ref', {static: false}) el: ElementRef;

doSomething(e) {
    // this reads false when you check the checkbox and true when you uncheck the check box:
    console.log('checkbox checked? ', e.target.querySelector('input[type="checkbox"]').checked);

    // I can't even use ViewChild with mat-checkbox. It is undefined:
    // 'cannot read property nativeElement of undefined'
    console.log('the native element: ', this.el.nativeElement);

  }

 // app.component.html
 <mat-checkbox
 (click)="doSomething($event)"
 >Bladder</mat-checkbox
 > 

为什么会event.target.querySelector('input[type=checkbox"]').checked给出错误的值?为什么是this.el未定义的?

标签: javascriptangularangular-material

解决方案


在最新的 Angular 8.0.0-rc.5 中,@ViewChild必须定义静态选项的地方包含了一项重大更改。

在 Angular 7 版本 (7.2.15) 中,此选项不存在,导致编译期间出现打字稿错误。

一种解决方法是将选项类型“强制转换”为任何

@ViewChild('ref', {static: false} as any) el: ElementRef;

对于this.el未定义,如果您的目标元素位于隐藏元素内,则可能会出现问题,请不要使用*ngIf. 而是使用一个类来显示/隐藏你被隐藏的元素。你可以在这里阅读更多

对于检查值看真假,可以尝试这样使用:

onChange(item, event) {
  if (event.checked) {            
     // Add checked / true vlaues to array
      this.selectedValues.push((item));
      // use for loop to iterate values to check true or false and perform operations
     }
       else{
        //remove unchecked / false values
        let index = this.selectedValues.indexOf(item);
        this.selectedValues.splice(index, 1);
      }
  }

在 html 中:

<mat-checkbox (change)="onChange(val1, $event)" [ngModel]="checkedVal">label1</mat-checkbox>

推荐阅读