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

How to effectively use graph paper with both major and minor grids in the background?

Looking to create a 100px by 100px image in Inkscape with major lines every 100px and minor lines every 10px. This will help verify viewport size when used as a repeating background. What's the best approach for this? Thinking of using #888888 for ma ...

positioning the cursor at the end of a content-editable div

When working with a contenteditable div, I encountered several issues specific to FireFox. To address these problems, I found that appending a br tag to the end of the div was necessary. <div id="testDiv" contentEditable="true"> Hey, click the butt ...

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

Are there any alternative methods to avoid duplication of Navbar link margin classes in Tailwind CSS?

It feels really repetitive to have to add margin classes to each LI manually on a non-dynamically generated menu. It almost seems as messy as using inline style attributes... Is there a more efficient way to handle this? While it may not be a big deal fo ...

`Ensuring uniform height for card titles`

So here's the scenario I'm dealing with: There seems to be an issue with alignment in the dark blue boxes when they are displayed in a flex container. The top box is not aligned properly with the one next to it. How can this problem be resolved? ...

"Enhancing User Interaction: The Dynamic Trio of Ajax, Php, and MySql in Comment

I have successfully developed a basic commenting system, featuring a form with two fields: name and comment. Upon submitting the values, it utilizes Ajax to dynamically add the comment to the existing page without refreshing the entire content. My next ob ...

Child Theme setup in progress! Beware of the error message: "Unable to access file: file_get_contents9(). The specified stream does not exist."

I am currently in the process of developing a child theme based on my existing theme (Tesseract 2). I have carefully followed the guidelines outlined here, but unfortunately, I keep encountering the following error: Warning: file_get_contents(/home/fletch ...

How to customize the appearance of an HTML checkbox using custom images for a unique

Does anyone know how to change the default style for: <input type=checkbox...> I want it to use my own styled pictures instead of the default style. Can anyone help? Thank you! ...

Leveraging ajax for showcasing page content in a floating div container

I am in need of creating a button on my page that, when clicked, will display a floating div above the page and load another internal page. I believe this can be achieved using Ajax, but I have no experience with it and don't know where to start. Her ...

Unexpected problem with redrawing HTML application in Android WebView

I created a basic nixie clock app using HTML and wrapped it in a WebView for use on Android. It consists of one HTML file, a JS file, a CSS file, and ten digit images. After a few hours, I noticed stripes appearing in the center of the screen where the an ...

Update the background color on the sidebar

Objective: I want to change the background of the class="col-sm-3 blog-sidebar" to match the color shown in the image below. Essentially, I am looking to update the sidebar background to reflect the picture's color. Challenge: How can this be ach ...

Tips on preserving CSS modifications made in Chrome Developer Tools Inspector to .vue file

Currently, I am in the process of setting up a new workflow where my goal is to streamline my work by using the Chrome DevTools Inspector to save any CSS changes directly to my .vue file. While the DevTools Workspaces feature can achieve this, it involves ...

What is the most effective method for tracking file upload progress using SSE?

I am currently working on creating a file upload progress feature that is compatible with older browsers using AJAX. In HTML5, there is the xhr.upload.progress event which works well for modern browsers, but I need an alternative for non-XHR2 browsers. I h ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

What is the best way to create a border with an inside radius?

Looking to design a div with an inner circle in the corner similar to the image below. Seeking assistance to find a solution for this issue. ...

Challenges arise when IE distorts featured images in a Wordpress theme

I've set up a Wordpress theme that utilizes featured images as header images on pages to allow clients to easily make modifications themselves. The header image container needs to be a fixed size (100% width of the page and 300px height), so I'm ...

Exploring Event Propagation in AngularJS

Currently, I am working on developing a web application using angularjs for the first time. A key feature that I aim to introduce is the ability for users to create a div in the main window upon clicking on an image in the menu. To achieve this functional ...

Is there a way to achieve a double background color effect in CSS while ensuring that the text is centered within the second background color element?

How can I achieve a layout similar to the one shown in this image: ul menu li tags Should I use two tags for each element? Here is an example: <ul class="menu"> <div class="outside"><li class="inside"><a href="#">Firefox</a ...

Utilize Ajax to open and close an HTML tag within separate div elements

I am facing a challenge in my project where I have to dynamically open and close a form using ajax. The form needs to be opened within a div, and then closed in another div below it like the following: Opening form (header div) $('#header').h ...

Achieving priority for style.php over style.css

Having trouble with theme options overriding default CSS settings in style.css. Here's what I have in my header.php: <link rel='stylesheet' type='text/css' media='all' href="<?php bloginfo( 'stylesheet_url&apo ...