繁体   English   中英

mat-checkbox 无法正确显示选中的值

[英]mat-checkbox does not properly display checked value

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

此外,如果我尝试将ViewChild与 mat-checkbox 一起使用,则会产生未定义的结果。 因此,我无法使用this.el.nativeElement到达元素。

我用这个隔离的 git 存储库来说明问题:

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未定义?

在最新的 angular 8.0.0-rc.5 中,包含了一项重大更改,其中@ViewChild必须定义 static 选项。

在 angular 7 版本(7.2.15)中不存在此选项,导致编译时出现 typescript 错误。

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

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

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

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

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>

我假设点击发生在检查值更新之前。 尝试(更改)事件并将#ref添加到您的复选框

html

 <mat-checkbox #ref (change)="doSomething($event)">Bladder</mat-checkbox> 

ts

 doSomething(e) {
   console.log(e.target.checked, this.el.nativeElement);
   // true/false, HTMLInputElement
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM