Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deselect radio button Angular 2?

I am trying to deselect a radio button in Angular 2. I tried the following code but it doesn't help.

.html

<div [formGroup]="myForm">
   <mat-radio-group matInput (click)= "resetRadio($event)" formControlName="RdoSel">
      <mat-radio-button *ngFor="let RadioOpt of RadioOpts" [value]="RadioOpt .id">{{RadioOpt .value}}</mat-radio-button>
   </mat-radio-group>
</div>

.ts

public RadioOpts= [
    { id: 'Market', value : 'Market'},
    { id: 'Segment', value : 'Segment'}
];

public resetRadio(event: any) {
if(myForm.get('RdoSel').value===event.target.value){
    myForm.get('RdoSel').setValue('false');
}

When I console.log(event.target.value) it returns <div> tags. Could someone please tell me how to deselect a radio button in Angular 2?

like image 264
Munna Babu Avatar asked Oct 30 '17 09:10

Munna Babu


2 Answers

Using reactive forms, we can use

yourFormName.controls['youRradioFormContolName'].reset();

this will reset you radio to unchecked.

like image 89
Sanjay Singh Avatar answered Oct 29 '22 17:10

Sanjay Singh


For me what it did worked was:

html:

<mat-radio-button value="1" 
                  (click)="clickRadio($event, 1)" 
                  [checked]="isRadioSelected(1)">1</mat-radio-button>

ts:

private radioVal:number;
public clickRadio(event:Event, value:any) {
    event.preventDefault();

    if (! this.radioVal || this.radioVal !== value) {
        this.radioVal = year;
        this.form.patchValue({myForm: this.radioVal});
        return;
    }

    if (this.radioVal === value) {
        this.radioVal = undefined;
        this.form.get('myForm').reset();
    }
}

public isRadioSelected(value:any) {
    return (this.radioVal === value);
}
like image 4
borracciaBlu Avatar answered Oct 29 '22 17:10

borracciaBlu