Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test">
      <mat-radio-button *ngFor="let option of options | filter:searchText" 
                class="cssForRow"
                [value]="option" 
                [checked]="option.isSelected"
                (change)="selectOption($event)">         
                        {{ option.value }}
                        <div class="info" [hidden]="!option.info">{{option.info}}</div>
            </mat-radio-button>
 </mat-radio-group>`

In the code snippet above, I have implemented radio buttons in a mat-radio-group using Angular Material. Each button corresponds to an object called "option". Currently, there is an issue where multiple options can have the same value, but different info. When selecting a radio button with a duplicate value, all buttons with that value are getting selected on the UI.

I've attempted solutions such as adding a name attribute to the mat-radio-group, changing the value attribute to a unique key, and implementing trackBy in ngFor, none of which resolved the issue. Can anyone provide assistance in fixing this problem?

Answer №1

"I am facing a situation where the option.value may be the same for multiple options, but the option.info differs between them".

In such cases, using a mat-radio-button is not recommended as you will not be able to determine which value has been selected accurately. It is assumed that you have an array of options

//"INCORRECT" it is unclear if you are adding the first or last option
options=[{value:1,info:'one'},{value:2,info:'two'},{value:1,info:'one bis'}]

you should consider using

//"CORRECT", Choosing the first option assigns a value of 101, where value%100=1
//       Selecting the last option assigns a value of 201, where value%100=1
//           and recognizing it as the last option
     
optionsValors=[{value:101,info:'one'},{value:102,info:'two'},{value:201,info:'one bis'}]

//or

optionsValors=this.options.map((x,index)=>
     ({value:index*100+x.value,info:x.info}))

Remember to use the modulo operator if you need the "actual value"

value=value%100

If your options.value data type is string, a similar approach can be taken by appending a letter and using substr

NOTE: Assuming you wish to store the value of the options in a variable. Since this is Angular, why not utilize [(ngModel)]?

<mat-radio-group [ngClass]="cssForGroup" name="test" [(ngModel)]="test">
      <mat-radio-button *ngFor="let option of options | filter:searchText" 
                class="cssForRow"
                [value]="option" >         
                        {{ option.value }}
                 <div class="info" [hidden]="!option.info">{{option.info}}</div>
       </mat-radio-button>
 </mat-radio-group>

Answer №2

My options array initially lacked unique IDs for each object, causing an issue with the functionality. After assigning unique IDs to all objects in the array, the problem was resolved. In this angular project, I utilized the event / API from mat-radio-button without needing to implement ngModel, although considering best practices is always essential.

Despite resolving the initial issue, there remains a mystery surrounding how mat-radio-button interacted with the lack of ID specification. Speculating that using [value] instead of [ngValue] may have played a role in the DOM or internal mechanisms, the addition of a unique 'id' key seemed to address the issue effectively.

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

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Having trouble bringing my custom-built Angular module into my Angular application

Currently considering the utilization of this Yeoman generator as a starting point for a small project that will contain several reusable form components to be published. The generator constructs a module and an example component, directive, pipe, and serv ...

The Swagger-ui tool condenses objects into query parameters, while the angular client that it generates does not

I'm currently working on a Spring Boot application that includes the following Rest function: @SecuredMaster @GetMapping(path = "/mitarbeiter") @Operation(security = {@SecurityRequirement(name = "jwt")}) public Page<MitarbeiterListRow> getMitar ...

Sonarqube coverage report is missing in Gitlab CI, but it works fine when running locally

I have encountered an issue with my Angular application deployed via GitLab CI. The deployment to the hosted Sonarqube instance is successful, but none of the code coverage reports are appearing unfortunately. Below is my GitLab yml file: stages: - te ...

What is the correct way to effectively share data between components using a service?

I've been diving into learning Angular 2 and successfully implemented data sharing between sibling components using input/output functions. Check out my working example here. // Our root app component import {Component, NgModule} from '@angular ...

Encountering issues when trying to import const enums in a webpack project using babel

Currently, I am working on a react project that was initially created using create-react-app. However, we later ejected and made extensive modifications to the webpack configuration. My current struggle lies in importing const enums from external libraries ...

What are some ways to troubleshoot the TypeScript React demonstration application in Chrome?

Debugging a TypeScript app in the Chrome debugger is a straightforward process. First, you need to configure the tsconfig.json file: "sourceMap": true, Next, install ts-node and set a breakpoint in your TypeScript code using "debugger;" ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...

The application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. shared/authorize.service.ts @Inje ...

ESLint is notifying that the prop validation for ".map" is missing, with the error message "eslint react/prop-types" occurring in a Typescript React environment

Hey everyone, excited to be posting for the first time! Currently, I'm working on a small project using Typescript and React. I've run into an issue with ESLint where it doesn't recognize that a prop variable of type string[] should have a ...

Issue with RxDB: Collection not found upon reload

Exploring the integration of RxDB in my Angular project. I wanted to start with a simple example: export const LANG = { version: 0, title: "Language Key", type: "object", properties: { key: { type: "string", primary: true } }, requ ...

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...

Update button Image upon click

Is there a way to swap the image on a button when it's clicked? I want my button to start with one icon, but then change to another icon once it has been clicked. How can I achieve this effect? Any suggestions on how to make this happen? Check out ...

Unlock the Potential: Empowering Users with Nativescript Firebase Sign

Recently, I embarked on the journey of developing apps using NativeScript and Angular. Looking for a reliable database source, I decided to go with Google Firebase. Successfully migrating my SQL data to the Firebase real-time database, I am now able to s ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...

Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet. <select name="shape_id" (change)="changeShape()"> <option *ngFor="let shape of shapes" [ngValue]="shape.name"> {{shape.name}} </option> </s ...

Creating interactive buttons within a card in Ionic 2

I created a card in Ionic 2 with the following structure. Upon clicking the card, it navigates to another page. <ion-content padding class="item item-text-wrap"> <ion-list> <ion-item *ngFor='let topic of topicList' text-wr ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...