javascript - mat-checkbox 无法正确显示选中的值
问题描述
我正在使用 Angular Material 的 mat-checkbox 组件。但是当我选中复选框时,如果我引用event.target.querySelector('input[type=checkbox"]').checked
,它会告诉我值为 false,当我取消选中复选框时,它会告诉我值为 true。它应该是相反的。
此外,如果我尝试ViewChild
与 mat-checkbox 一起使用,它会产生未定义。因此,我无法使用this.el.nativeElement
.
我用这个孤立的 git repo 说明了这个问题:
以下是 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
必须定义静态选项的地方包含了一项重大更改。
在 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>
推荐阅读
- pca - 如何在 UMAP 中选择正确的维数?
- c++ - 如果我在堆上声明一个类实例,它的所有成员也会在堆上吗?
- flutter - 如何在颤动中将焦点设置在材质按钮上
- flask - ModuleNotFoundError:没有名为“apsheduler”的模块
- azure-notificationhub - Azure 通知中心上单个消息遥测的生存时间是多少?
- javascript - 将多个 id 附加到 api 调用
- angular - 我可以从 angular/nativescript PWA 项目中删除 zone.js 包或其他任何包而不破坏项目吗
- mysql - 从子实体中为 IN 子句中的每个元素获取 100 行
- php - PHP 代码将从一个 MySQL 表中选择,但不会从另一个表中选择
- java - 如何将字符串时间戳读入形式为 Fri Jul 17 12:41:20 IST 2020 的 Java 日期?