我有一个广播组:
<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',
},
]
}
当我单击收音机时,我的模型没有更新, {{categoryModel.name}} 还是空的,那是什么问题,我该如何更改?
答案 0 :(得分:0)
您要绑定到单选按钮的值,该值等于类别的ID。
您可以使用change事件获取当前所选类别的名称,例如:
change(category_id){
this.categoryModel.name = this.categories.find(c => c.id == category_id).name
}
此处的示例:https://stackblitz.com/edit/angular-qeejnn?file=src%2Fapp%2Fapp.component.ts
答案 1 :(得分:0)
您可以绑定categoryModel.name
而不是绑定categoryModel
。要使其正常工作,请将选项值设置为category
,并确保单选按钮具有相同的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>
有关演示,请参见this stackblitz。
答案 2 :(得分:0)
//您可以直接复制并粘贴代码并根据需要进行自定义
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>