A guide on updating radio button values with Reactive Forms

Inside my component class, I am attempting to set a form radio button value to 1:

import { FormGroup, FormControl } from '@angular/forms';

export class RadioComponent implements OnInit{
    pageForm: FormGroup;

    ngOnInit() {
        this.pageForm = new FormGroup({
            'gender': new FormControl(1)
        });
    }
}

However, upon loading the page, the radio button does not default to "Male" and both options appear blank:

<div class="form-group">
    <label for="gender">Gender</label>
    <div class="radio">
        <label>
            <input type="radio" name="gender" formControlName="gender" value=1>Male
        </label>
    </div>
    <div class="radio">
        <label>
            <input type="radio" name="gender" formControlName="gender" value=0>Female
        </label>
    </div>
</div>

How can I correctly load the radio button value from my component class?

Answer №1

To have one of them checked by default manually, simply include the "checked" tag as shown below:

<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=1 checked>Male
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio" name="gndr" formControlName="gndr" value=0>Female
    </label>
</div>

Edit

If you wish to set the default value as a string type, specify it in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl('1')
    });

component.html

...
<input type="radio" formControlName="gndr" value=1>
...

If you prefer the default value to be a number type, configure it in the FormControl:

component.ts

this.pageForm = new FormGroup({
      'gndr': new FormControl(1)
    });

component.html

...
<input type="radio" formControlName="gndr" [value]=1>
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a new instance with a parameter in TypeScript using a generic function

In my code, I have numerous classes that extend an interface. These classes can contain arrays of objects from each other. For example, a school can have multiple students, but both classes implement the same interface. To streamline this process, I decid ...

What could be the reason it's not functioning as expected? Maybe something to do with T extending a Record with symbols mapped

type Check<S extends Record<unique, unknown>> = S; type Output = Check<{ b: number; }>; By defining S extends Record<unique, unknown>, the Check function only accepts objects with unique keys. So why does Check<{b:number}> ...

What are the steps to set up NextJS 12.2 with SWC, Jest, Eslint, and Typescript for optimal configuration?

Having trouble resolving an error with Next/Babel in Jest files while using VSCode. Any suggestions on how to fix this? I am currently working with NextJS and SWC, and I have "extends": "next" set in my .eslintrc file. Error message: Parsing error - Can ...

How to Include HttpClient in an Angular Service

Looking for a service that utilizes http requests? import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root&a ...

Angular version 4 JSONP request callback

Currently, I am working on the migration of an Angular 1 application to Angular 4. One particular challenge I have encountered is a jsonp call to an endpoint over which I have no control. In the Angular 1 app, the following code snippet is being used: js ...

The process of implementing a React onchange event in Angular using ngModelChange

html: <mat-form-field appearance="outline" class="inputBox"> <input matInput name="total" placeholder="0.00" [ngModel]="total" (ngModelChange)="handleOnChange('total', $event ...

Employing async await for postponing the execution of a code block

I have been working on an Angular component where I need to perform some actions after a data service method returns some data asynchronously. Although I attempted to use async/await in my code, I feel that I may not have fully understood how it works. Her ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

Prevent loading data in Angular 5 by handling errors from undefined objects

Is there a way to avoid console errors from undefined objects? Imagine I have the following code: name : string; constructor(private data: DataService) { this.data.name.subscribe(res => this.name = res); } In my HTML, I have this: <p> {{name}} ...

Increase by 30 minutes from the minimum value and decrease by 30 minutes from the maximum value in Ionic date time

Looking to add a customized Ionic date time picker with min and max capabilities. If the minimum time is selected, it should automatically add 30 minutes, while selecting the maximum time should subtract 30 minutes. Any suggestions on how to achieve this? ...

Guide to integrating location-based QR code verification

Currently, I am developing an Angular application where I am utilizing an npm package to generate QR codes. One of my main requirements is to incorporate location-based functionality into the QR code system. For instance, if a user is at a specific hotel a ...

Error in Angular: Unable to find a provider for the dependency of a dependency

Currently, I am in the process of developing a small toy application in Angular that consists of various classes, including ProductDetailComponent and ProductService. The ProductService class contains a method responsible for making an HTTP GET request for ...

Dynamically attach an Angular 2+ directive from a component

Looking to dynamically attach a directive from a component based on a condition. My attempt using @HostBinding doesn't seem to be working. import { Component, Directive, HostBinding } from '@angular/core'; @Component({ selector: &apos ...

Learn how to configure gulp-typescript to automatically generate individual JavaScript files for each TypeScript file within the same directory

My interest lies in utilizing the gulp-typescript module for handling typescript compilation. My goal is to set up a configuration where each typescript file translates into one javascript file in the corresponding directory, similar to how it works with t ...

Angular 8: Issue with setErrors not reflecting on the template when marking a control as invalid

In my component, I am using the following code: this.frmGroup.controls['dorms'].setErrors({'incorrect': true}); For debugging purposes, I have added the following to my template: {{this.frmGroup.controls['dorms'].invali ...

Cypress - Adjusting preset does not impact viewportHeight or Width measurements

Today is my first day using cypress and I encountered a scenario where I need to test the display of a simple element on mobile, tablet, or desktop. I tried changing the viewport with a method that seems to work, but unfortunately, the config doesn't ...

Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website. I would like it to detect when the URL changes using a HostListener. @HostListener('window:hashchange', ['$event']) onHashChange(event) { this.checkCu ...

Efficient code for varying layouts of disabled Angular Material buttons

I've been wondering if there's a simpler way to customize the appearance of a disabled button using Angular Material. Currently, I achieve this by utilizing an ng-container and ng-template. While this method gets the job done, the code is not ve ...