angular - 我需要所有带有 [(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
}
解决方案
您的代码中有很多错误。指出几点
您不能在标签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
推荐阅读
- javascript - 将字符串中的所有数字四舍五入
- bash - 在脚本中插入多行“find”,每行都有自己的命令“-exec”,在“-exec”上发出错误信号:缺少参数
- sql - 如何创建一个 SQL 列,其值取决于(映射到)现有查阅列的值?
- android - Android minSdk 覆盖所有库
- swift - 用户默认值尝试设置非属性列表对象
- r - 找不到绘图函数对象的错误
- javascript - 如何在 Nodejs mocha 中声明一个全局数组?
- c# - C# - 不能在同一源的 WPF 项目中使用 .NET Framework 项目中的类
- canvas - 带有 clearRect 和 AudioContext 的画布清除路径
- ssl - URL 阻止机器人