Setting the selected value of a radio button in an edit form: a step-by-step

I'm currently developing an edit form using ReactiveFormModule. My goal is to display data in the edit form with various input elements such as textboxes, dropdowns, radio buttons, and checkboxes. I've been successful in setting values for textboxes and dropdowns using the setValue method, but I'm facing challenges when it comes to setting value for a Radio group.

Typescript

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl, ValidationErrors, FormControlName } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable, EMPTY, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
})
export class AddComponent implements OnInit {
  stateList : any;
  cityList: any;
  genderList: any;
  hobbyList: any;
  name: FormControl;
  age: FormControl;
  state : FormControl;
  city: FormControl;
  myform: FormGroup;
  gender: FormControl;
  hobby: FormControl;
  file: FormControl;
  email: FormControl;
  confirmEmail: FormControl;

  submitted = false;

  constructor(private http: HttpClient) {
    // Form controls initialization
    this.name = new FormControl("", [Validators.required, Validators.email, Validators.minLength(6), Validators.pattern("")]);
    this.age = new FormControl("27", [checkageValidator]);
    this.state = new FormControl("");
    this.city = new FormControl("", Validators.required);
    this.gender = new FormControl("");
    this.hobby = new FormControl("");
    this.file = new FormControl("");
    this.email = new FormControl("");
    this.confirmEmail = new FormControl("", [compareEmail]);

    // FormGroup creation
    this.myform = new FormGroup({
      name: this.name,
      age: this.age,
      state : this.state,
      city: this.city,
      gender: this.gender,
      hobby: this.hobby,
      file: this.file,
      email: this.email,
      Cemail: this.confirmEmail
    });

    // Data initialization
    this.stateList = [{value : 1, text: "Gujarat"}, {value : 2, text : "Maharastra"}];
    this.cityList = [{ value: 1, text: "Ahmedabad", stateid: 1 }, { value: 2, text: "Rajkot", stateid: 1 }, { value: 3, text: "Gandhinagar", stateid: 2 }];
    this.genderList = [{ value: 1, text: "Male", selected: "checked" }, { value: 2, text: "Female", selected: "" }];
    this.hobbyList = [{ value: 1, text: "Games", checked:false }, { value: 2, text: "Tracking", checked:false }, { value: 3, text: "Swimming", checked:false }];
  }

  ngOnInit() {
    // Setting initial values for certain fields
    this.myform.controls["name"].setValue("Hardik");
    this.myform.controls["state"].setValue("1");
    
    // Setting default selection for Radio button
    this.genderList.find(i=>i.value == 2).selected == "checked";
  }
}

HTML

<form novalidate [formGroup]="myform" (ngSubmit)="SubmitData(myform)">
    <div class="row">
        <div class="col-lg-12">
            <div class="col-xs-4">
                Name:
...

<p>The challenge lies in setting the value for my RadioButton using <code>setValue. Currently, I am adjusting the selected property within my JsonData, which may not be the best approach according to best practices. What alternative approaches could I consider?

Answer №1

To determine if the radio input is checked, you can compare the current form value with the radio input value.

<label class="radio-inline" *ngFor="let g of genderList">
  <input type="radio" [value]="g.value" name="gender" formControlName="gender" 
         [checked]="myform.get('gender').value == g.value">
  {{g.text}}
</label>

Next, in the component, assign the necessary value to the form.

this.myform.controls["gender"].setValue(2);

Check out the StackBlitz Demo.

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

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

There seems to be an issue with the React Native FlatList: It appears that there is no overload matching this call and some

I am currently learning React Native and attempting to create a basic chat room application. I am facing an issue with the FlatList component that I can't seem to resolve. Even though I have provided both the data prop and renderItem prop to the FlatL ...

The attribute 'value' is not present in the object of type 'Readonly<{}>'

My current project involves creating a form that will dynamically display content based on the response from an API. The code I am working with is structured as follows: class Application extends React.Component { constructor(props) { super(props); ...

Determine if a radio button is in an enabled or disabled state

<div id="statusOptions"> <label><input type="radio" name="status" value="T" checked> Temporary Waiver</label> <label><input type="radio" name="status" value="P"> Never Expires</label> <label><i ...

Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array: const toSort = [ ['key2', FormGroup: {controls: {order: 2}}], ['key1', FormGroup: {controls: {order: 1}}] ] ...

Utilizing Form Validation in Angular 4

In the process of developing a straightforward Angular application that utilizes Twitter Bootstrap and jQuery to showcase employee data. I have hardcoded 4 sets of data which are displayed in a table, as shown in the attached image. The addition of an "Add ...

What is the best way to incorporate TypeScript into a simple JavaScript project and release it as a JavaScript library with JSDoc for TypeScript users?

Issue: I have encountered difficulties finding an efficient solution for this. Here's a summary of what I attempted: To start, ensure that allowJs and checkJs are both set to true in the tsconfig.json, then include the project files accordingly. Ty ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

The string returned from the Controller is not recognized as a valid JSON object

When attempting to retrieve a string from a JSON response, I encounter an error: SyntaxError: Unexpected token c in JSON at position In the controller, a GUID is returned as a string from the database: [HttpPost("TransactionOrderId/{id}")] public asyn ...

How can you define a function type for a rest parameter in Typescript?

At this point, I have a function that takes in two parameters: param 'a' as a string and 'b' as a function that returns a string. My intention is to call it using a rest parameter and specify the types accordingly. However, on line 10 ...

Sign in to Azure for an Angular application within the iFrame of another Angular application

I have two separate Angular apps, both enabled with Azure AD login. When accessed separately in the tab, they function properly - redirecting and obtaining the token without issue. Now, I aim to make Angular 1 the Parent and Angular 2 the child within a s ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...

Stopping the infinite refresh issue in your React webpack application

Every time I modify the TS file, Webpack keeps refreshing the page without stopping. The console message reads: "@ebpack 5.66.0 compiled successfully" I've searched online and experimented with various plugins, but none of them seem to solve the issu ...

Is your Typescript struggling to infer types correctly?

I created a function that converts an Array into a Map: function toMap<T,TKey,TElement>(items: Array<T>, keySelector: (item: T) => TKey, elementSelector: (item: T) => TElement ): Map<TKey,TElement> { var ma ...

What are the advantages of combining the website URL and API URL within the Angular service?

When deploying my application in a production environment, I encounter an issue with the URL addresses. The web address is , while the API address is . However, when making a request to the API through Angular, the URLs get concatenated into . This issue d ...

The grouping functionality of the Material UI Buttongroup seems to be failing to properly

Working on a review score list currently, where I've set up a RadioGroup with RadioButtons. However, the issue is that the RadioButtons are not aligning properly with the RadioGroup. The goal is to have the radiobuttons styled similarly to the exampl ...

Utilizing an external TypeScript class without the need for importing it

Let's consider a scenario where we have a class named Constant. The requirement is to make this class accessible globally without the need for importing, is there a way to achieve this? In the constant.ts file: class Constant { public stati ...

When the required attribute in Angular2 is conditional and the value is empty, the field will be adorned with the ng-valid class

In my current project using Angular 2.3.1, I have incorporated the following HTML element into a component template: <input class="form-control" type="text" id="password" name="password" placeholder="Password" [attr.required]="requirePasswd ? true : n ...