Set a default selection for radio buttons in Angular template-driven forms

I'm having an issue with setting a default selection for a radio button in my template-driven form. Here's the relevant part of my code:

   <div class="donut-form-promos">
    <span>Promo:</span>
    <div class="donut-form-promos-choices">
      <input
        type="radio"
        name="promo"
        [value]="'newPromo'"
        rquired
        ngModel
        #promo="ngModel"
      /><span>New</span>
      <input
        type="radio"
        name="promo"
        [value]="'limitedPromo'"
        required
        ngModel
        #promo="ngModel"
      /><span>Limited</span>
      <input
        type="radio"
        name="promo"
        [value]="'clubPromo'"
        required
        ngModel
        #promo="ngModel"
      /><span>Club memeber</span>
      <input
        type="radio"
        name="promo"
        [value]="undefined"
        required
        ngModel
        #promo="ngModel"
        [checked]="'checked'"
      /><span>None</span>
    </div>
  </div>

I've also uploaded this example on StackBlitz, you can view it here.

Any assistance would be greatly appreciated.

Answer №1

In Angular, radio button elements with the same name attribute are treated as a single control system. This means that multiple radio buttons with the same name act as one input with only one output value (similar to a select element with multiple options). The selected radio button determines the value of the control. Conversely, in Angular, the value of the control can also determine which radio button is selected. For instance, if Radio Button A has a value of "1" and Radio Button B has a value of "2", setting the control's value to "2" during initialization will automatically select Radio Button B.

To bind the ngModel directive to a default value in a radio button element, use the following syntax:

[ngModel]="defaultValue"

Example TypeScript component:

import { Component, VERSION } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;
  defaultPromo = 'limitedPromo';
  icons: any[] = [
    { id: 1, name: 'icon-1' },
    { id: 2, name: 'icon-2' },
    { id: 3, name: 'icon-3' },
  ];
  onNgSubmit(form: NgForm) {
    if (form.valid) {
      console.log(form);
    } else if (form.invalid) {
      form.form.markAllAsTouched();
    }
  }
}

Template:

<form class="custom-form" (ngSubmit)="onNgSubmit(formInstance)" #formInstance="ngForm">
  <label>
    <span> Name :</span>
    <input
      type="text"
      name="name"
      class="input"
      minlength="5"
      required
      ngModel
      #name="ngModel"
    />
    <ng-container *ngIf="name.touched && name.invalid">
      <div class="error-message" *ngIf="name.errors?.required">
        This field is required
      </div>
      <div *ngIf="name.errors?.minlength">Please enter at least 5 characters.</div>
    </ng-container>
  </label>
  <label>
    <span> Icons :</span>
    <select
      name="icon"
      class="input input--select"
      required
      ngModel
      #icon="ngModel"
    >
      <option *ngFor="let icon of icons" [ngValue]="icon.name">
        {{ icon.name }}
      </option>
    </select>
    <ng-container *ngIf="icon.touched && icon.invalid">
      <div class="error-message" *ngIf="icon.errors?.required">
        Please select an icon
      </div>
    </ng-container>
  </label>
  <button type="submit" class="btn btn--green">Submit</button>
  <pre>{{ formInstance.form.value | json }}</pre>
</form>

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

Delete the child element if it is present in an HTML document

removeConnection(event) { let parentElement = document.getElementById('RemoveElement'); let childElement = document.getElementById(event.target.id); parentElement.removeChild(childElement); } Whenever I try to remove the child ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

Using Python and Selenium, you can locate an element inside another element

I've got the xpath for an element: /html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[6]/div/div/div/div[1] Inside that div, there's another element: /html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[ ...

The text is placed over a beautiful SVG image, adding a decorative touch to

Im interested in incorporating an SVG image of a curly bracket below and between two words, similar to the example shown. Considering the need for responsiveness, I initially attempted adding the image directly into the HTML within a span tag positioned b ...

Creating a moving background for a loading bar with HTML5 and Shadow DOM is currently underway

Can anyone help with animating the progress bar using the HTML5 <progess> tag? I've been able to customize the Shadow DOM elements successfully, but I'm having trouble animating the background (repeating linear gradient). It seems to work i ...

New post: The vue component that was released lacks CSS (NPM)

For the first time, I am releasing a Vue component on NPM and everything seems to be in order, except for one issue - the CSS is missing. While it functions perfectly when tested locally, after installing the npm package in a test project and importing the ...

The intl-tel-input dropdown feature is malfunctioning on mobile browsers

Currently, I have integrated the intl-tel-input library into my project for selecting international telephone numbers from a dropdown menu. https://i.sstatic.net/vPfpd.png While accessing the application on a web browser, the country flags display correc ...

The fit-content max-height property is not functioning properly in Firefox

This CSS approach is effective in browsers like Chrome. p.ex1 { max-height: fit-content; height: 250px; border:solid 1px black; overflow: auto; } The goal is to utilize the full height, allowing scrolling when necessary, while also adjusti ...

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

The browser has disregarded a CSS rule

Hey there, I have a question that may seem silly, but I just can't seem to find the answer anywhere. Please take a look at this fiddle: I need to remove #Navigation in the CSS declaration below: #Navigation .stretch { ... } so it should look like ...

Difficulty encountered when trying to use Bootstrap tooltip with Bootstrap icon

Attempting to implement bootstrap tooltips on bootstrap icons with the following code: <body> <script> const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

html - displaying a new page within the content of the current page

I have a question about basic HTML knowledge that I find embarrassing Is it possible to open or load a second page within my first page? I want a menu button that will load the second page. <li class="current"><a href="first.html" target = "myC ...

Is it possible to execute an Ajax Request using JQuery?

I've been attempting to update the content within a <div> using a JQuery Ajax Call, but unfortunately I'm encountering some difficulties. Whenever I click on the onclick <a> element, nothing seems to happen. Below is the code that I a ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Assistance required: The database is not found upon page reload. How can this be resolved?

My HTML5 code has created a database with create, add, delete, and print operations. However, the ObjectStore is re-created every time I load the page, and the additional values stored are not present upon reloading the page. What could be wrong with my ...

Understanding the Functions of Angular Providers and Implementing Them

Just starting out with Angular and following a tutorial from this video. I decided to experiment by adding providers :[EmployeeService] to both employee-list.component.ts and empployee.component.ts within the @component section. However, this led to an err ...

Looking to set the "min" attribute for an input type="date" in HTML5 with a specific date format preselected?

My upcoming date has a specific format as detailed below. Date_received = Tue Apr 05 2016 00:00:00 GMT+0530 (India Standard Time) To set the 'min' attribute for the HTML5 input type="date" datepicker, I need to initialize it using the following ...

"Click here to access the downloadable content obtained through web scraping

I am looking to automate a task using Python where I need to get a PDF file from a website with fileid 8426 and date 03312021. Visit this link: Click on the "Download PDF" button Save the downloaded file to a directory After exploring, I came across a P ...