angular - 如果在 ngFor 中使用,如何获取 mat-checkbox 检查值
问题描述
我正在尝试获取所有已检查的复选框并对其执行某些功能。
<div class="outerdiv" *ngFor="let item of items">
<mat-checkbox>Hello</mat-checkbox>
<div>
<button (click)="filterSelectedItems()"></button>
filterSelectedItems(){
let outerdiv = this.element.nativeElement.querySelectorAll('.outerdiv');
for(let i = 0; i < outerdiv.length; i++){
let option = outerdiv[i].querySelector('mat-checkbox');
if(option.checked){
this.filterItem+=option.innerText;
}
}
解决方案
您可以在此StackBlitz Link中获得 Total工作示例
您的 html 是,并且onChange
复选框getCheckbox()
事件触发。这里我们传递模板引用变量#checkBox
。
<div *ngFor ="let item of items">
<mat-checkbox #checkBox [value]="item" (change)="getCheckbox(checkBox)">
{{item}}
</mat-checkbox>
</div>
<div *ngFor="let checkedItem of checked">
<span> selected Key is: <strong> {{checkedItem.value }} </strong> :
<strong> {{checkedItem.checked}} </strong>
</span>
</div>
您可以使用这样的方式获取文件中#checkBox
的数组...component.ts
@ViewChildren()
QueryList
@ViewChildren ('checkBox' ) checkBox:QueryList<any>;
checked = [];
items =['one','two', 'three', 'four'];
getCheckbox(checkbox){
this.checked = []; // resetting each Time new event is fire.
// filtering only checked vlaue and assign to checked variable.
const checked = this.checkBox.filter(checkbox => checkbox.checked);
// then, we make object array of checked, and value by checked variable
checked.forEach(data => {
this.checked.push ({
'checked' : data.checked,
'value': data.value
})
})
}
推荐阅读
- reactjs - 如何在不扩展到另一行的情况下将电子邮件包装在相应的单元格中?
- javascript - babel 意外令牌反应模块构建失败
- c++ - 我如何处理 TMP 以避免打印任何内容
- python - 如何在beautifulsoup中获取分页数据
- azure-web-app-service - 在 Azure Windows WebApp 上构建 Strapi 返回 500 错误
- javascript - 如何从可用于 android 活动的 webview 中获取数据?
- javascript - Thymeleaf 的 Css 和 Javascript 问题
- python - 如何迭代页面并获取每篇新闻文章的链接和标题
- python - 如何将 ffmpeg complex_filter 转换为 ffmpeg-python
- r - 如何在国家地图上标注特定坐标的点