【发布时间】:2021-02-07 01:47:27
【问题描述】:
我想取消选择单选按钮,但是在搜索了很多之后..我没有找到答案。所以我选择使复选框作为单选按钮工作的方式(仅单选)。它工作得很好,但是当我无法将 ngmodel 绑定到复选框时。 我想要这样的复选框
- 项目1 ID 姓名
- 项目2 ID 姓名
- 项目 3 ID 姓名
我需要从项目列表中选择一个复选框项目(ID 和名称中的一个)。
【问题讨论】:
我想取消选择单选按钮,但是在搜索了很多之后..我没有找到答案。所以我选择使复选框作为单选按钮工作的方式(仅单选)。它工作得很好,但是当我无法将 ngmodel 绑定到复选框时。 我想要这样的复选框
我需要从项目列表中选择一个复选框项目(ID 和名称中的一个)。
【问题讨论】:
请使用 [(ngModel)] 检查此代码。
HTML
<div *ngFor = "let item of data ; let i = index">
<input type="checkbox" name="cb1" [(ngModel)]="item.IsSelected" (change)="toggleSelection(i)" /> {{item.name}}
</div>
组件
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
data : any = [
{'id': 1 , 'name': 'item-1'},
{'id': 2 , 'name': 'item-2'},
{'id': 3 , 'name': 'item-3'},
{'id': 4 , 'name': 'item-4'}
];
toggleSelection(i){
this.data.forEach((item, index) => {
if(index != i){
this.data[index].IsSelected = false
}
})
}
getSelectedItem(){
const selectedItem = this.data.filter( (item) => item.IsSelected );
console.log("selected option is ", selectedItem);
}
}
【讨论】: