首页 > 解决方案 > 我需要所有带有 [(ngModel)] 的单选按钮

问题描述

当我只需要一个按钮时,我只选择了一个按钮。当我点击任何按钮时,只有最后一个按钮被选中。

component.html
<input type="button" (click)="someFunction(categoryInput.value)" value="click me too" />
      <div id="categorybox">
      <tr  class="categories" *ngFor="let category of categories">
        <td>
            <input type="radio"  id={{category.categoryName}} [(ngModel)]=selectedCategory name="category" value="{{category}}" (click)=selectCategory(category)/>


          <label for ={{category.category}} >{{category.categoryName}}</label>
        </td>
      </tr>
component.ts
export class HomeComponent implements OnInit {
  page= 0;
  home: Home[];
  categories: Category[];
  selectedCategory: Category;
  selectCategory (category) {
    console.log(category.category);
    // do something here
    // this.selectedCategory will be the selected value
    // the category will be the value that was just selected
 }

标签: angulartypescript

解决方案


您的代码中有很多错误。指出几点

您不能在标签tr内包含div许多属性标签中缺少引号 input不需要结束标签等等

假设您的类别为

categories: any[] = [
{
  id: 1,
  name: "Category 1"
},
{
  id: 2,
  name: "Category 2"
},
{
  id: 3,
  name: "Category 3"
},
{
  id: 4,
  name: "Category 4"
}
];

你的模板应该看起来像

<table>
    <tr class="categories" *ngFor="let category of categories">
        <td>
            <input type="radio" id="{{category.id}}" name="category" value="{{category.id}}" (click)="SelectCategory(category)">
          <label for ={{category.id}}>{{category.name}}</label>
      </td>
  </tr>
</table>

并且您可以访问组件类中的选定类别

this.SelectCategory = category;

Stackblitz 在https://stackblitz.com/edit/angular-k7fp7v


推荐阅读