【发布时间】:2019-03-10 15:16:39
【问题描述】:
我想用对象而不是字符串来绑定单选按钮。为此,我尝试了与以下类似的代码:
<div *ngFor="let object of objects">
<input type="radio" id="category" [(ngValue)]="object">
</div>
在 Angular 中有没有办法将对象与单选按钮的值绑定?
【问题讨论】:
我想用对象而不是字符串来绑定单选按钮。为此,我尝试了与以下类似的代码:
<div *ngFor="let object of objects">
<input type="radio" id="category" [(ngValue)]="object">
</div>
在 Angular 中有没有办法将对象与单选按钮的值绑定?
【问题讨论】:
ngValue 将不可用于单选按钮。它仅适用于 select 列表。
您可以使用[value] 属性绑定语法将对象分配为选定单选按钮的值。
将此用于您的模板:
<div *ngFor="let object of objects">
<input
(change)="onCheck()"
[(ngModel)]="selectedCategory"
type="radio"
id="category"
[value]="object">
{{ object.categoryValue }}
</div>
在你的课堂上:
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);
}
}
这里有一个Sample StackBlitz 供您参考。
【讨论】: