多次单击时未选中“角材垫"单选按钮 [英] angular material mat radio button unchecked on multiple click

查看:96
本文介绍了多次单击时未选中“角材垫"单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何清除第二次单击时选择的<mat-radio-button> (在已选择之后)

How can I clear <mat-radio-button> selected on second click (after it is already selected)

我知道我可以通过复选框实现此行为,但我只允许选择一项.

I know I can implement this behavior with checkbox but i need to allow select only one item.

有帮助吗?

我的代码如下:

<mat-radio-group name="WasFamilyMemberPresent">
    <mat-radio-button *ngFor="let item of lookupNoYes" [value]="item.Code" >
       {{item.Desc}}
    </mat-radio-button>
</mat-radio-group>

推荐答案

您可以执行以下操作来实现此目的.

You can do the following to accomplish this.

为按钮#button分配模板引用,并将其传递给组件方法(click)="checkState(button)"

Assign a template reference to the button #button and pass it to the component method (click)="checkState(button)"

 <mat-radio-button #button class="example-radio-button" *ngFor="let season of seasons" [value]="season" (click)="checkState(button)">

在组件中创建一个局部变量,以将按钮值存储在checkState()

Create a local variable in the component to store the button value for comparison in checkState()

 currentCheckedValue = null;

DI Renderer2从按钮上移开焦点

DI Renderer2 to remove focus from the button

 constructor(private ren: Renderer2) { }

setTimeout中包装逻辑以将其置于摘要循环中,检查是否存在局部变量,以及当前值是否等于参数值...如果为true,则取消选择,移除焦点,并为null局部变量...否则,为未来的比较.

Wrap logic in setTimeout to put it on the digest cycle, check if local variable exist and if current value equals argument value... if true deselect, remove focus and null local variable... else set local variable for future comparison.

checkState(el) {
    setTimeout(() => {
      if (this.currentCheckedValue && this.currentCheckedValue === el.value) {
        el.checked = false;
        this.ren.removeClass(el['_elementRef'].nativeElement, 'cdk-focused');
        this.ren.removeClass(el['_elementRef'].nativeElement, 'cdk-program-focused');
        this.currentCheckedValue = null;
        this.favoriteSeason = null;
      } else {
        this.currentCheckedValue = el.value
      }
    })
  }

Stackblitz

https://stackblitz.com/edit/angular-c37tsw?embed=1&file=app/radio-ng-model-example.ts

这篇关于多次单击时未选中“角材垫"单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆