【问题标题】:How to bind input radio value to object in angular?如何将输入单选值绑定到角度对象?
【发布时间】:2019-03-10 15:16:39
【问题描述】:

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

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

在 Angular 中有没有办法将对象与单选按钮的值绑定?

【问题讨论】:

    标签: angular html frontend


    【解决方案1】:

    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 供您参考。

    【讨论】:

    • 它运行良好。非常感谢您的帮助。
    猜你喜欢
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2019-06-26
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多