[英]How to get mat-checkbox checked value if used in ngFor
我正在尝试获取所有选中的复选框并对其执行某些功能。
<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 是,并且 checkbox getCheckbox()
事件的onChange
触发。 这里我们传递模板引用变量#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>
您可以像这样使用@ViewChildren()
和QueryList
在component.ts
文件中获取#checkBox
数组...
@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
})
})
}
您可能会在触发mat-checkbox
的change
事件时获得选中的值。
<div class="outerdiv" *ngFor="let item of items">
<mat-checkbox [checked]="item.value" (change)="getCheckedValue($event)">Hello</mat-checkbox>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.