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?
Using reactive forms, we can use
yourFormName.controls['youRradioFormContolName'].reset();
this will reset you radio to unchecked.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With