4

I want to bind radio buttons with objects instead of strings. For that I tried a similar code to the following:

<div *ngFor="let object of objects">
    <input type="radio" id="category" [(ngValue)]="object">
</div>

Is there a way in Angular to bind objects with the values of radio buttons ?

1 Answer 1

7

ngValue won't be available for radio buttons. It's only available with select lists.

You can use the [value] attribute binding syntax to assign an object as the value of the selected radio button.

Use this for your template:

<div *ngFor="let object of objects">
  <input 
    (change)="onCheck()" 
    [(ngModel)]="selectedCategory" 
    type="radio" 
    id="category" 
    [value]="object">
    {{ object.categoryValue }}
</div>

And in your Class:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  selectedCategory;

  objects = [
    {categoryName: 'Category1', categoryValue: 'Category1'},
    {categoryName: 'Category2', categoryValue: 'Category2'},
    {categoryName: 'Category3', categoryValue: 'Category3'},
  ];

  onCheck() {
    console.log(this.selectedCategory);
  }

}

Here's a Sample StackBlitz for your ref.

Sign up to request clarification or add additional context in comments.

3 Comments

It's working perfectly. Thank you very much for the help.
One of the best explanations I came accross, thanks. Works like a charm in Angular 17+
But two way binding not working, i.e, if i pass object in selectedCategory its not preselected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.