angular material mat radio button unchecked on multiple click

不打扰是莪最后的温柔 提交于 2020-07-05 05:11:32

问题


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.

Any help?

My code look like :

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

回答1:


You can do the following to accomplish this.

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)">

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

 currentCheckedValue = null;

DI Renderer2 to remove focus from the button

 constructor(private ren: Renderer2) { }

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




回答2:


I have simplified Marshal's code here

https://stackblitz.com/edit/angular-c37tsw-zho1oe

I removed setTimeout and Renderer2 import and it would seem to work even without these but with an event.preventDefault().




回答3:


I'm not sure what answer you are looking for since the angular material radio buttons default behaviour is to only allow one selected item. (This is what i assume you are asking based off of your question)

Are you trying to create behaviour where the user can deselect all radio buttons?



来源:https://stackoverflow.com/questions/53612626/angular-material-mat-radio-button-unchecked-on-multiple-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!