Reputation: 443
I have a radio group:
<div class="btn-group">
<div class="btn btn-outline-secondary"
*ngFor="let category of categories">
<input
type="radio"
[value]="category.id"
[(ngModel)]="categoryModel.name">
{{category.name}}
</div>
</div>
ts
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
})
export class Test {
categories: {};
categoryModel = {name: ''};
constructor(private modalService: NgbModal) {
this.categories = [{
id: 1, name: 'test1',
},
{
id: 2, name: 'test2'
},
{
id: 3, name: 'test3',
},
]
}
When I click my radio, my model doesn't update, {{categoryModel.name}} is still empty, what is wrong with it, how can I change this?
Upvotes: 1
Views: 5198
Reputation: 2392
Use [checked] for each attribute
<input type="radio" name="category" [checked]="button1" [value]="category" [(ngModel)]="categoryModel">
<input type="radio" name="category" [checked]="button2" [value]="category [(ngModel)]="categoryModel">
Upvotes: 0
Reputation: 41
// Working code you can directly copy and paste the code and customize as per your requirement
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
categoryList: {};
selectedCategory = { name: "" };
constructor() {
this.categoryList = [
{ id: 1, name: 'Option1' },
{ id: 2, name: 'Option2' },
{ id: 3, name: 'Option3' },
{ id: 4, name: 'Option4' },
{ id: 5, name: 'Option5' },
]
}
}
<div>
<h1> Seleted Option: {{selectedCategory.id}}-
{{selectedCategory.name }}</h1>
<div class="btn btn-outline-secondary"
*ngFor="let cat of categoryList">
<input
type="radio"
[value]="cat"
[(ngModel)]="selectedCategory">
{{cat.name}}
</div>
</div>
Upvotes: 1
Reputation: 73761
Instead of binding categoryModel.name
, you can bind categoryModel
. To make it work, set the option values to category
and make sure that the radio buttons have the same name
.
<div class="btn-group">
<div *ngFor="let category of categories" class="btn btn-outline-secondary">
<input
type="radio"
name="category"
[value]="category"
[(ngModel)]="categoryModel">
{{category.name}}
</div>
</div>
See this stackblitz for a demo.
Upvotes: 0
Reputation: 715
You are binding to the value of the radiobutton which is equal to the id of the category.
You can use the change event to get the name of the currently selected category like:
change(category_id){
this.categoryModel.name = this.categories.find(c => c.id == category_id).name
}
An example here: https://stackblitz.com/edit/angular-qeejnn?file=src%2Fapp%2Fapp.component.ts
Upvotes: 0