I require that all of my radio buttons are equipped with the [(ngModel)] directive

Every time I click on a button, only the last one is selected. How can I ensure that only one button gets selected at a time?

component.html
<input type="button" (click)="someFunction(categoryInput.value)" value="click me too" />
      <div id="categorybox">
      <tr  class="categories" *ngFor="let category of categories">
        <td>
            <input type="radio"  id={{category.categoryName}} [(ngModel)]=selectedCategory name="category" value="{{category}}" (click)=selectCategory(category)/>


          <label for ={{category.category}} >{{category.categoryName}}</label>
        </td>
      </tr>
component.ts
export class HomeComponent implements OnInit {
  page= 0;
  home: Home[];
  categories: Category[];
  selectedCategory: Category;
  selectCategory (category) {
    console.log(category.category);
    // do something here
    // this.selectedCategory will be the selected value
    // the category will be the value that was just selected
 }

Answer №1

Your code contains several errors that need to be addressed. Here are a few examples:

It is not valid to have a tr element inside a div tag. Many of your properties are missing quotation marks. input tags do not require a closing tag, among other issues.

If you have categories defined as follows:

categories: any[] = [
{
  id: 1,
  name: "Category 1"
},
{
  id: 2,
  name: "Category 2"
},
{
  id: 3,
  name: "Category 3"
},
{
  id: 4,
  name: "Category 4"
}
];

Your template should be structured like this:

<table>
    <tr class="categories" *ngFor="let category of categories">
        <td>
            <input type="radio" id="{{category.id}}" name="category" value="{{category.id}}" (click)="SelectCategory(category)">
          <label for={{category.id}}>{{category.name}}</label>
      </td>
  </tr>
</table>

To access the selected category in your component class, you can use:

this.SelectCategory = category;

You can view the updated code on Stackblitz at https://stackblitz.com/edit/angular-k7fp7v

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 there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

Seamless database migrations using sequelize and typescript

I've been exploring the concept of generating migration files for models that already exist. When I use the "force: true" mode, tables are automatically created in the database, so I find it hard to believe that creating migration files automatically ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

Is there a way to sort a MUI Datatable based on the value rather than the custom body render content?

Previously, the temperature (of type Number) was displayed as a string with "° C" appended to it before implementing custom filter options. Despite this formatting change, the value was sort-able (ascending and descending). However, after adding the custo ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

Shift objects using ng2-dragula from a designated location

I am working on an Angular 4 application that utilizes the library ng2-dragula. My goal is to enable drag and drop functionality for items, but restrict dragging to only when initiated from a specific designated area (marked with an icon), rather than from ...

Error message: "Unidentified variable in the code snippet from MUIv5 sample."

Achieving the Objective To implement a drawer sidebar in MUI5 that can be toggled open and closed by the user, I am exploring the documentation for the Drawer component as well as referencing an example. Encountering an Issue Upon copying the code from ...

The function map.set is not recognized in Angular 2

I am trying to update some values in my map. For instance, consider the following scenario: The AddressBook class looks like this: export class AddressBook { constructor( public social: Map<string, string> = new Map<string, string>(), ...

Using Angular 4 Material to pass an array of objects to a dialog box

Greetings, I am currently attempting to pass an array of objects to a Material dialog. Below is my approach: Model export interface IProducts{ recordname: string; comments: [{ comment: string }] } The component class contains the ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Using Optional Route Parameters in Angular with @ngrx

Just like the ngrx/example-app, I am in the process of developing a user interface that allows users to search for specific items by inputting a text string. I want to enhance the user experience by updating the URL with an optional parameter (query=searc ...

Encountered an issue: e.results.map is not recognized as a function in TypeScript version

Here's the code snippet I am working on: Search.tsx import * as React from 'react'; import axios from 'axios' import Suggestions from './Suggestions' const API_KEY:string = "process.env" const API_URL:string = 'h ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

Error during Ng 16 upgrade - npm ERR! Peer dependency conflict found: @angular/[email protected]

I am currently in the process of upgrading my Angular version from 11 to 16. While this Angular documentation has been quite helpful, I am encountering various errors and challenges. Let me provide you with the versions I am working with: Angular CLI: 11. ...

Transforming the timestamp to a date object using Angular and Typescript

As a newcomer to Angular 2.0, I've been delving into new concepts in order to grasp it better. However, despite encountering this common issue multiple times and reading through various solutions, I haven't been able to find the answer to my prob ...

What is the process for obtaining the index number of a specific type within an Array type in typescript?

Take a look at this TypeScript code snippet: type Data = [string, number, symbol]; // Array containing different types // To access 'symbol', you would do this: type Value = Data[2]; //--> symbol // Now the challenge is to find the index of ...

Is there a way to retrieve the length from a state observer variable?

Currently, I am in the process of learning NgRx and I have encountered a situation where I need to replace this template code: <ion-button *ngIf="myVar.length > 0" ... > I want to use a code that retrieves the value from a state observ ...

The journey of an Angular and NGXS store application culminates in a seamless loop of store updates

Currently, I am utilizing NGXS as the store mechanism in my application. Within the store, there is a list of conditions that are displayed using the RuleEngineAddViewStepperConditionComponent component and the *ngFor directive on the UI. Each condition ha ...