MatCheckbox preventDefault()和event.checked值 [英] MatCheckbox preventDefault() and event.checked value
问题描述
如何实现材料"复选框,以使其在默认情况下不会被选中/取消选中(例如,在事件上调用preventDefault()
),并且还从事件中获取checked
值?
How can I achieve a Material checkbox so It won't get checked/unchecked by default (eg. calling preventDefault()
on the event) and also get the checked
value from the event?
似乎我只能达到其中一个条件.使用(click)
事件,我无法获取复选框的值;使用(change)
事件,我无法阻止默认复选框的值更改(仅在基础HTTP请求成功的情况下,我才更改复选框的值).
It seems like I can only achieve one of the conditions. Using the (click)
event I cannot get the checkbox's value and using the (change)
event I can't prevent the default checkbox value change (I will only change the checkbox value if the underlying HTTP request was successful).
Stackblitz: https://stackblitz.com/edit/matcheckbox-checked >
Stackblitz: https://stackblitz.com/edit/matcheckbox-checked
<mat-checkbox
[checked]="checked"
(click)="onClick($event)"
>onClick me!</mat-checkbox>
<br/>
<mat-checkbox
[checked]="checked"
(change)="onChange($event); false"
>onChange me!</mat-checkbox>
export class CheckboxOverviewExample {
checked: boolean = false;
onClick(event) {
event.preventDefault();
console.log('onClick event.checked ' + event.checked);
console.log('onClick event.target.checked '+event.target.checked);
}
onChange(event) {
// can't event.preventDefault();
console.log('onChange event.checked '+event.checked);
}
}
(click)
事件显示undefined
值,但成功阻止了事件传播,(change)
事件显示了值,但将传播事件.
The (click)
event prints undefined
values, but successfully prevents the event propagation, the (change)
event prints the value but will propagate the event.
相关问题:
- https://github.com/angular/material2/issues/1142
- https://github.com/angular/angular/issues/2042
- https://github.com/angular/material2/issues/13156
- https://github.com/angular/material2/issues/1142
- https://github.com/angular/angular/issues/2042
- https://github.com/angular/material2/issues/13156
推荐答案
如果要手动选中复选框,则@ViewChild获取元素的引用,然后使用checked这样设置值true或false
If you want to check the check box manually @ViewChild get the ref of the element then use checked to set the value true or false like this
@ViewChild('ref') ref;
onClick(bool){
this.ref._checked=bool;
}
示例: https://stackblitz.com/edit/matcheckbox-checked-ybru81
事件处理时的相同示例: https://stackblitz.com/edit/matcheckbox-checked -a1le6o
Same example while event handling: https://stackblitz.com/edit/matcheckbox-checked-a1le6o
这篇关于MatCheckbox preventDefault()和event.checked值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!