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

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

Change icons in Ionic 5 when selecting a tab

How can I change my tab icons to outline when not selected and filled when selected? The Ionic 5 Tabs documentation mentions a getSelected() method, but lacks examples on its usage. I plan to utilize the ionTabsDidChange event to detect tab clicks, then ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

A guide on eliminating repetitions from an array of objects by utilizing the spread operator

I am working with an object array that has a unique key called "id": var test = [ {id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""}, {id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""}, {id: ...

Navigating between components in different modules using Angular 5

I have a home component within the homeModule and a contactUs component within the contactModule. When I click cancel on the contactUs component, it should redirect me to the Home component. Here are the routes: import {NgModule} from '@angular/cor ...

How to reference an array from one component to another in Angular 2

Within my AddUserComponent, I have a public array declared like this: public arr: Array<any> = [] This array stores the names of users. Now, I need to access these values in another component called AddTopicComponent in order to display the user&a ...

Tips for eliminating top and bottom spacing in angular material mat-row/mat-cell elements

I am working with an Angular material mat-table where I want to adjust the row height to fit only the text, without any extra space above and below it. I attempted to directly modify the mat-cell like this, but unfortunately, it did not work: <mat-cell ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. Below is the code snippet: word ...

Issue with ngClass not updating during Route Event

I am using a bottomNavigation component that changes its style to indicate which route we are currently on. Below is the template for the bottom-navigation: class="menu-icon" [ngClass]="{ 'active-item': buttonActivated.value == '/my-goa ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Enhance your Primeng split button with an added icon when selected

Is it possible to add a tick icon when the user selects the click option in a split button? Any advice on how to achieve this would be appreciated. Thank you. For example, similar to the image below: https://i.stack.imgur.com/owOgE.png ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

Even with the inclusion of headers in the server code, the Cross-Origin Request is still being

I have a basic API set up in Express/Node and a simple Angular application for posting blogs. However, I am encountering an issue when trying to access the /contribute route using the POST method. The error message that I receive on both Chrome and Firefox ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

Revise: Anticipated output missing at conclusion of arrow function

Here is the code snippet that I am having trouble with: <DetailsBox title={t('catalogPage.componentDetails.specs.used')}> {component?.projects.map(project => { projectList?.map(name => { if (project.id === name.id) { ...

Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required. export type Recommendation = { id?: string, name: string, type?: string, tt: string, isin?: string, issuer: string, quantity?: nu ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

angular2 fullCalendar height based on parent element

Currently, I am using angular2-fullcalendar and encountering an issue with setting the height to 'parent'. The parent element is a div but unfortunately, it does not work as expected. The navigation bar appears fine, however, the calendar itself ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...