Adjust the radio button's color within an ngFor loop when it is selected

When I select an item from my radio button list, I want to change its appearance by altering the background-color, text color, or highlighting. Unfortunately, due to the use of an ngFor loop for rendering the items, I am unable to achieve this as desired. Currently, on click, all the items in the list change color from red to blue instead of just the selected one.

I attempted using li::selection in CSS but it did not yield the expected results.


<div class="container">
<div class="col-sm-12 form-group">
    <p><strong>Select Your Subject</strong></p>
    <ng-container *ngFor="let subs of allSubjects">
      <ul id="subList">
        <li [ngClass]="{'blue' : toggle, 'red': !toggle}">
          <label>
            <input checked type="radio" name="ClassTimesSubjects" 
 [(ngModel)]="subs.classTimeSubjectsName"
[value]="subs.classTimeSubjectsName" 
[(ngModel)]="ClassTimesSubjects" #ClassSubjects="ngModel" required
(click)="enableDisableRule()">
           {{subs.classTimeSubjectsName}}
           <img [src]="subs.classTimeSubjectsImage" id="subPics">
          </label>
        </li>
      </ul>
    </ng-container>
  </div>
</div>

Typescript...


   toggle = true;
   status = "Enable";
   public allSubjects: Array<any>;

   enableDisableRule(job) {
      this.toggle = !this.toggle;
      this.status = this.toggle ? "Enable" : "Disable";
   }

CSS...


.blue {
  background-color: blue;
}

.red {
  background-color: red;
}
 

Answer №1

It is recommended to utilize the following code snippet:

<ul>
  <li *ngFor="let item of data" [ngClass]="{'blue' : selectedValue==item.id, 'red': selectedValue!=item.id}" >
    <input type="radio"  name="group" [(ngModel)]="selectedValue" [value]="item.id"/> {{item.name}}</li>
</ul>

Typescript

selectedValue=1
  data = [
    { id: 1, name: 'A', selected: false },
    { id: 2, name: 'B', selected: true },
    { id: 3, name: 'C', selected: false }]
}

View on Stackblitz

Answer №2

Utilize ngModel and Data Binding for this task. Refer to the code snippet below.

<ul>
  <li [ngClass]="{'blue' : checked, 'red': !checked}">
    <input type="checkbox"  [(ngModel)]="checked" />
  </li>
</ul>

For the complete code, click here - https://stackblitz.com/edit/angular-xsfx9q

Answer №3

For the desired outcome, implement indexed toggling for each element within ngFor.

  1. Assign indexes for toggling to each radio button.
  2. Upon selection of any radio button, reset all toggle array values to false.
  3. Set the specific index to true every time a radio button is selected.
  4. When a radio button is selected, change the background color of the elements from red to blue.

Sample code - https://codesandbox.io/s/angular-2be5t

app.component.js

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "CodeSandbox";
  toggle = [];
  status = "Enable";
  allSubjects = [
    {
      classTimeSubjectsName: "test1",
      classTimeSubjectsImage: ""
    },
    {
      classTimeSubjectsName: "test12",
      classTimeSubjectsImage: ""
    }
  ];

  enableDisableRule(i) {
     let idx = 0;
while (idx < this.allSubjects.length) {
  this.toggle[idx] = false;
  idx++;
}

this.toggle[i] = !this.toggle[i];
this.status = this.toggle[i] ? "Enable" : "Disable";
  }
}
<div class="container">
  <div class="col-sm-12 form-group">
    <p><strong> Select Your Subject</strong></p>
    <ng-container *ngFor="let subs of allSubjects; let i =index">
      <ul id="subList">
        <li [ngClass]="{'blue' : toggle[i], 'red': !toggle[i]}">
          <label>
            <input
              checked
              type="radio"
              name="ClassTimesSubjects"
              [(ngModel)]="subs.classTimeSubjectsName"
              [value]="subs.classTimeSubjectsName"
              [(ngModel)]="ClassTimesSubjects"
              #ClassSubjects="ngModel"
              required
              (click)="enableDisableRule(i)"
            />
            {{ subs.classTimeSubjectsName }}
            <img [src]="subs.classTimeSubjectsImage" id="subPics" />
          </label>
        </li>
      </ul>
    </ng-container>
  </div>
</div>

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

Circular dependency detected between TransferHttpCacheModule, LocalizeRouterModule, and TranslateModule

I am in need of the following modules for my project: TranslateModule LocalizeRouterModule TransferHttpCacheModule This particular combination of modules seems to be causing a cyclic dependency issue. TranslateModule with TransferHttpCacheModule - works ...

Guide on transporting PNG files over the boundary

I am working with two specific css commands. code h1 { background: #000000; border-radius: 6px; color: #fff; display: block; font: 40px/60px "Sans", Inconsolata, "Lucida Console", Terminal, "Courier New", Courier; padding: 40px 40px; text-align: center; ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

A guide to building a three-column card layout using the Bootstrap row class

How can I display the content of my page, which is presented in cards, in three different columns using bootstrap 4 row class? I am currently working with Laravel 5.8 and bootstrap 4. The carousel and nav bar functions are working well. The code snippet ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

What is the best way to add animation to switch between table rows?

I am looking to add animation effects when table rows appear and disappear. Initially, I attempted using a CSS transition, but it did not work due to the change in the display property. Subsequently, I opted for an animation, which provided the desired o ...

The HTML/JS output displays a table with missing horizontal borders

Why aren't my horizontal borders showing up in the output section? Take a look at the code and screenshot below: I want to include horizontal borders and prevent the date fields from moving to the row below. https://i.sstatic.net/qO1KC.png I would li ...

Is it possible to make an asp:Panel extend beyond its boundaries to the right when dynamically incorporating controls into a webpage?

Currently, I am working on a solution to dynamically add controls to an asp:Panel on a website, ensuring that they all remain on the same line. Despite setting a specific width and adding overflow:auto, the controls still wrap to the next line when there i ...

Elements styled as inline blocks with static dimensions, irregular in size

Is there a way to ensure that all three boxes are displayed at the same level? Currently, box 2 appears below box 1 and 3 due to having less content. I believe there must be some styling element missing to make each div display at an equal level regardless ...

Shopify revamping the design of the collections

Looking to enhance the layout of a collection page by moving from a single column to having at least three items per row. The current layout can be viewed here Proposed new layout example shown here 1: Below is a snippet of the code I believe needs adj ...

Some browsers are failing to display the navigation bar on my website

After working on my website, www.alexanderpopov.org, I encountered an issue with the navigation bar disappearing on some computers and browsers. I'm using css to style it, but the problem persists. Below is the HTML code for your reference. Any advice ...

Customizing Dropdown Menus with Bootstrap

Is there a way to make the select element appear as a list, similar to this image: https://i.sstatic.net/1IB8T.jpg Apologies, I'm still a beginner at this. Thank you in advance. ...

Align the text to the right within a display flex container

Below is the code snippet: <div className="listContent"> <div> <div className="titleAndCounterBox"> <div className="headerListTitle">{list.name}</div><br /> <div ...

Is there a way to customize a chart in Ionic 2 to resemble the image provided?

Hello there, I am currently using import {Chart} from 'chart.js'; to generate my chart; however, I am facing some difficulties. My goal is to create a chart similar to the one displayed below. Warm regards //Generating the doughnut this.dou ...

Is it possible to implement a feature in Angular and Bootstrap where the toggle menu can be closed by clicking anywhere on the page, rather than just the toggle button

I'm working on an Angular project where I've implemented a navbar component. The navbar is responsive and includes a toggle button that appears when the browser window is resized. This button allows users to hide or display the menus. One issue ...

Show an HTML image with the file chosen through the FileDialog prompt

After spending about four hours searching for a method to display the image file chosen by FileDialog in a browser within an img tag, I came across various pages suggesting updating the src attribute of the img tag with the content of the file. However, th ...

Radio button validation issue in Angular not resolving

Issue with radio button validation in Angular form. Even when a radio button is not selected, the form submits without displaying any error messages. HTML Code <form [formGroup]="feedbackFormWithArray" (ngSubmit)="submitData()"> ...

Background image for Semantic-UI modal

Is it possible to add a background image to a Semantic-UI Modal? <modal ng-model="dc.show_leaderboard" class="leaderBoard"> <i class="close icon" ng-click="dc.close_modal()"></i> <div class="header">Header</div> </mo ...

How can I vertically align a photo or image on Facebook?

Can anyone explain how Facebook manages to vertically align its photos without using padding or margins? I've looked into their img tag and its parent, but neither seem to have any spacing properties. Although there is a vertical-align attribute prese ...

What is the best way to rearrange three divs into two columns?

I am trying to rearrange the order of three divs in my markup layout. The desired layout is to display div one first, followed by three underneath it in the first column. Then, in the second column, I want to only show div two. My current CSS configuratio ...