我需要使用[[ngModel)]的所有单选按钮

时间:2019-10-02 16:15:39

标签: angular typescript

当我只需要一个按钮时,我只会选择其中一个按钮。当我单击任何按钮时,只会选择最后一个按钮。

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
 }

1 个答案:

答案 0 :(得分:0)

您的代码中有很多错误。指出一些

您不能在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;

https://stackblitz.com/edit/angular-k7fp7v上的Stackblitz