Home > Enterprise >  How do you use radio button to toggle between true and false values? Using Angular and Reactive Form
How do you use radio button to toggle between true and false values? Using Angular and Reactive Form

Time:06-18

Here is the radio button that I have in a FormArray.

   <input
               
                type="radio"
                formControlName="correctAnswer"
                value=""
                name="correctAnswer"
                
              />

When the radio is selected, I want the value I get returned to be 'true'. When it's unselected, I want the value returned to be 'false'. This value is to be kept within the radio input itself, so that it displays in the value of my FormArray.

Any thoughts? I considered doing checkboxes, but I can only have one selected at a time. I basically need a checkbox that acts like a radio in the sense that it only one FormArray can be true.

Thanks in advance.

CodePudding user response:

In my opinion, it´s better use a checkbox:

<mat-checkbox formControlName="active" id="activeFilter">Active</mat-checkbox>

but if you want use a radiobutton maybe it will work if you initialize this value in your formGroup.

this.formGroup = new FormGroup({
  active: new FormControl(false),
});

And specify the values ​​in html:

<mat-radio-group aria-label="Select an option" formControlName="active">
  <mat-radio-button value="true">True</mat-radio-button>
  <mat-radio-button value="false">False</mat-radio-button>
</mat-radio-group>

CodePudding user response:

Radio buttons aren't meant to hold true/false values in a sense that the toggled state is true false. The value should be either present or not - toggled or not. I would also suggest checkbox for such operations (which could look like radio buttons if needs be). But... we could do something like this:

/**
 * @title Radios with ngModel
 */
@Component({
  selector: 'radio-ng-model-example',
  templateUrl: 'radio-ng-model-example.html',
  styleUrls: ['radio-ng-model-example.css'],
})
export class RadioNgModelExample {

  seasons: any[] = [
    { name: 'Winter', value: false },
    { name: 'Spring', value: false },
    { name: 'Summer', value: false },
    { name: 'Autumn', value: false },
  ];
  
}
<label id="example-radio-group-label">Pick your favorite season</label>
<br />
<ng-container *ngFor="let season of seasons">
  <mat-radio-button
    name="{{season.name}}"
    
    [checked]="season.value === true"
    [value]="season.value"
    (click)="season.value = !season.value">
    {{season.name}} current value is {{season.value}}
  </mat-radio-button>
  <br />
</ng-container>

Working example: https://stackblitz.com/edit/angular-lcrva2-cxphui?file=src/app/radio-ng-model-example.html

If you need formControls on the radio buttons, each radio button should be in within its own radio group for a template driven form control, or use reactive approach and read values from seasons[].

  • Related