如何以角度将输入无线电值绑定到对象?

Sak*_*akr 3 html frontend angular

我想用对象而不是字符串绑定单选按钮。为此,我尝试了与以下类似的代码:

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

Angular 有没有办法用单选按钮的值绑定对象?

Sid*_*era 5

ngValue将不可用于单选按钮。它仅适用于select列表。

您可以使用[value]属性绑定语法将对象分配为所选单选按钮的值。

将此用于您的模板:

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

在你的课堂上:

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

这是供您参考的示例 StackBlitz