[英]Keep checkbox checked in angular
Using angular 9 and some custom input I made the following =>使用 angular 9 和一些自定义输入,我做了以下 =>
https://stackblitz.com/edit/angular-ivy-rgsatp https://stackblitz.com/edit/angular-ivy-rgsatp
I would like to prevent user from disabling a radio button that is currently checked, so I changed the following in radio-button.component
我想阻止用户禁用当前选中的单选按钮,所以我在radio-button.component
中更改了以下内容
from从
<label [class]="'radio-container ' + cssClass || ''">
<div class="radio">
{{ checked }}
<input type="checkbox" [checked]="checked" [(ngModel)]="checked" (click)="click()" />
<span class="checkmark"></span>
</div>
<div style="margin-left: 20px;">
<ng-content></ng-content>
</div>
</label>
I remove the binding of ngModel to do [ngModel]="checked"
and force the state on the input.我删除了 ngModel 的绑定以执行[ngModel]="checked"
并强制输入 state。
https://stackblitz.com/edit/angular-ivy-x2sszw https://stackblitz.com/edit/angular-ivy-x2sszw
The problem I face i, although the check stay true, the css do not, and I do not understand why it's not forced to check.我面临的问题是,虽然检查保持正确,但 css 没有,我不明白为什么不强制检查。
Check and uncheck are browser events, perhaps you should use event.preventDefault()
to stop default behavior of browser选中和取消选中是浏览器事件,也许你应该使用event.preventDefault()
来停止浏览器的默认行为
Like喜欢
<input type="checkbox" [checked]="checked" [ngModel]="checked" (click)="click($event)" />
And和
click(event): void {
if (this.checked) {
event.preventDefault();
}
if (!this.disabled) {
this.checked = true
this.emitChange()
}
}
Stackblitz堆栈闪电战
https://stackblitz.com/edit/angular-ivy-pomkvy https://stackblitz.com/edit/angular-ivy-pomkvy
Also I would like to add two more points另外我想补充两点
this.disabled
.不要添加不必要的变量,例如您的示例this.disabled
。 Because Angular runs its cycle on every event.因为 Angular 在每个事件上都运行它的周期。 So it might affect performance所以可能会影响性能Try like this像这样试试
<label [class]="'radio-container ' + cssClass || ''">
<div class="radio">
{{ checked }}
<input type="checkbox" [checked]="checked" [ngModel]="checked" (click)="click()" [attr.disabled]="checked ? true : null" />
<span class="checkmark"></span>
</div>
<div style="margin-left: 20px;">
<ng-content></ng-content>
</div>
</label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.