Selected Angular Radio Button

Back in the good ole days of basic HTML and CSS, I was able to achieve the following:

input:checked+label {
  background-color: #f00;
}
<div class="col-xs-6">
  <input type="radio" id="template-1" name="template" value="template1" checked>
  <label for="template-1">Example 1</label>
</div>
<div class="col-xs-6">
  <input type="radio" id="template-2" name="template" value="template2">
  <label for="template-2">Example 2</label>
</div>

However, when attempting to replicate the same snippet within an Angular form using ngModel, the CSS doesn't take effect upon loading. It only applies after clicking one of the buttons.

Check out the Angular Plunkr example here

It seems like the radio button is not recognizing the checked attribute? How can I ensure that my Angular radio button starts off checked and also triggers the CSS styling?

Answer №1

Kindly modify your component according to the instructions provided:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Greetings {{name}}</h1>
        <div *ngFor="let example of examples" class="col-xs-6">
          <input type="radio" id="example.value" name="example" [(ngModel)]="template" [value]="example.value">
      <label for="example.value">{{example.display}}</label>
    </div>
  `,
  styles: [`input:checked + label{background-color: #f00;}`]
})
export class AppComponent implements OnInit{ 
  name = 'Angular';
  public examples = [
    { value: 1, display: 'Example 1' },
    { value: 2, display: 'Example 2' }
];
 template:string;


ngOnInit(){
   this.template = this.examples[0].value;
  }
}

We have also included a link to a plunkr demo for further reference.

Visit the Plunkr here

Answer №2

Latest Plunker Update

Check out the updated code here!

  <div class="col-xs-6">
        <input type="radio" id="template-1" name="template" value="template1" checked = "{1 == 1}">
        <label for="template-1">Example 1</label>
    </div>

Answer №3

Here is a helpful solution for AngularJS. The user is seeking assistance with Angular...

In Angular, you have the ability to dynamically add a class based on the value of the ng-model

<input type="radio" ng-model="bool" ng-class="bool ? 'true' : 'false'">

When $scope.bool is true (or when the radio button is checked), this will add the "true" class

I haven't tested this code myself, but it should work or at least point you in the right direction.

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

TypeScript code runs smoothly on local environment, however encounters issues when deployed to production

<div> <div style="text-align:center"> <button class="btnClass">{{ submitButtonCaption }}</button> <button type="button" style="margin-left:15px;" class="cancelButton" (click)="clearSearch()"> {{ clearButtonCapt ...

What is the most concise way to align one table row in the middle and another at the top?

Is there a way to align different rows in a table vertically with minimal code? I have a table with 3 rows, and I want the first two rows to be aligned vertically to the top, while the third row should be vertically aligned to the middle. If I try to def ...

Update Angular2 application's routes dynamically

Currently, I am developing an application that involves dynamically loading modules based on JSON data. I am looking to modify the app's routing depending on the user's permission to view certain modules. Can you provide guidance on how to accomp ...

Creating a sleek CSS drop-down navigation menu

I seem to be facing an issue with the side navigation drop down menu. Below are the link and CSS code: <nav id="nav"> <div class="menu-main_nav-container"><ul id="menu-main_nav" class="menu"><li id="menu-item-270" class="menu-it ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

CSS font attribute stylus variable

Can you help me troubleshoot this issue with the variable in stylus that is setting the font attribute using shorthand syntax? button-font = 100 16px Helvetica Neue', Helvetica, Arial, sans-serif I'm encountering the following error message: ...

Position the checkbox to the left of the label

I currently have a checkbox with ripple effects. The label text is displayed before the checkbox in the code. However, I'd like to change the order so that the checkbox comes before the label text. Occasionally, the entire div expands and contracts. ...

Is there a way to duplicate the background-style:contain effect on an image?

It is important to note that the image source must be declared in the HTML code as it will be dynamic, and therefore background cannot be used here. HTML <div class='some-form'> <form> <button>...<button> <i ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

Initial page load experiencing issues with paroller.js functionality

Upon hard refreshing the page in the middle section, there seems to be an issue with the paroller js transform: translateY(); CSS effect not functioning properly on the <div class="col col-6" data-paroller-factor="0.4" data-paroller-type="foreground" da ...

Error message: "Unable to locate HTML container when trying to create a child element in am

Whenever I navigate away from this page and then come back, the chart does not load. Instead, it displays an error message saying html container not found at createChild However, if I refresh the page, the chart will appear again. The issue seems to be i ...

Tips for converting string values from an Observable to numbers using the parseFloat() method

Having trouble converting text to numbers for geolocation coordinates. My model consists of a site with an ID and an array of points as a property. Rather than creating a relationship between site and points, I've structured it differently. In my cod ...

Angular 6 - accepting an HTTP GET request as the app loads

Upon the initial startup of my Angular application, just before its pages are loaded onto the user's browser, I aim to retrieve certain information from the HTTP request that triggered the app's launch. More precisely, I am looking to obtain the ...

The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once ...

The ngfor loop seems to be caught in an endless cycle of continuously executing functions and

I am currently working on a sophisticated reporting solution. Essentially, I have created a table using an ngFor loop where I have implemented certain conditions that allow the user to view details of a clicked element by expanding and collapsing it. The ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...

Problem with datepicker interface not aligning properly with Bootstrap grid

I am encountering a challenge with aligning the input controls in my UI design. Specifically, I am trying to create rectangular borders/containers around each set of input controls and looking for a way to achieve this using Booststrap. For reference, y ...

Issue with HTTP Interceptor not being effective when making service calls

I've implemented an interceptor to automatically add headers to each HTTP request without manual intervention. However, I'm facing an issue where the service call inside my interceptor is not triggering for some reason. Below is the code snippet: ...

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

What is the secret to getting this nested observable to function correctly?

Currently, I am working on an autocomplete feature that dynamically filters a list of meals based on the user's input: export class MealAutocompleteComponent { mealCtrl = new FormControl() filteredMeals: Observable<Array<Meal>> live ...