多次单击时未选中角度材料垫单选按钮单击、单选、按钮、角度

2023-09-07 09:25:40 作者:温如暖风

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.

怎么在PowerPoint中制作图像分析图

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>

解决方案

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

 
精彩推荐
图片推荐