我有一个广播组:
<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}}仍然是空的,它有什么问题,我怎么能改变它?
您绑定到radiobutton的值,该值等于类别的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
你可以绑定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。