Angular 每行仅选择一个
我有五行,其中有两个复选框,每个复选框都是通过循环生成的,并使用属性绑定和单击函数。当前,当我单击一个项目时,列中的所有元素也被选中,但我希望按行实现这一点。有什么方法可以做到这一点吗 我的组件 my component.htmlAngular 每行仅选择一个,angular,typescript,Angular,Typescript,我有五行,其中有两个复选框,每个复选框都是通过循环生成的,并使用属性绑定和单击函数。当前,当我单击一个项目时,列中的所有元素也被选中,但我希望按行实现这一点。有什么方法可以做到这一点吗 我的组件 my component.html 像所有人一样 {{item} 比如: 不喜欢: PS:当我点击按钮时,它应该选中列中的所有类似复选框。部分问题在于,您试图用当前逻辑跟踪1:many。对于这些,最好对数据进行结构化,以捕获每个对象(水果)的属性。然后,您可以使用[(ngModel)]绑定所有内容
像所有人一样
{{item}
比如:
不喜欢:
PS:当我点击按钮时,它应该选中列中的所有类似复选框。部分问题在于,您试图用当前逻辑跟踪1:many。对于这些,最好对数据进行结构化,以捕获每个对象(水果)的属性。然后,您可以使用
[(ngModel)]
绑定所有内容
TypeScript
import { Component, OnInit } from '@angular/core';
enum CheckBoxType { LIKEME, DISLIKE, NONE };
@Component({
selector: 'app-select-one',
templateUrl: './select-one.component.html',
styleUrls: ['./select-one.component.css']
})
export class SelectOneComponent implements OnInit {
public fruits = ["apple", "straw berry","orange","plum","grapes"].map( f => ({ name: f, like: false, dislike: false }));
check_box_type = CheckBoxType;
currentlyChecked: CheckBoxType;
constructor() { }
ngOnInit() {}
selectAllLike(){
this.fruits.forEach( f => {
f.like = true;
f.dislike = false;
})
}
}
HTML
<button (click)="selectAllLike()" >Like All</button>
<div *ngFor="let item of fruits; let i = index">
<p>{{item | json}}</p>
Like: <input type="checkbox" name="test" [(ngModel)]="item.like" [disabled]="item.dislike">
Dislike : <input type="checkbox" name="test" [(ngModel)]="item.dislike" [disabled]="item.like">
<hr>
</div>
像所有人一样
{{item | json}}
比如:
不喜欢:
另一方面,我会在表格中使用角度材质MatTable
。它更干净,功能更齐全
以下是使用函数切换不同状态的版本:
你能创建stackblitz吗?@mwilson这是我的stackblitz链接。我可以更改您的
公共水果结构吗?那肯定是最容易的办法。请说吧!谢谢,但还有一个问题。我仍然可以在所有行中选择喜欢和不喜欢。它应该是其中的一个,而不是两个。是的,你应该使用单选按钮,而不是复选框(从技术上讲)。请投票/打分作为答案,我很乐意进一步协助。单选按钮不能取消选中。最重要的是我想让uncheck属性可用。我更新了我的答案。您可以轻松应用[disabled]
属性来管理重复问题。另一个选项是绑定一个切换另一个选项的(单击)
事件,它是真的。谢谢@mwilson。复选框的目标是实现带有未选中选项的单选按钮属性。我们必须能够在喜欢和不喜欢之间切换。
import { Component, OnInit } from '@angular/core';
enum CheckBoxType { LIKEME, DISLIKE, NONE };
@Component({
selector: 'app-select-one',
templateUrl: './select-one.component.html',
styleUrls: ['./select-one.component.css']
})
export class SelectOneComponent implements OnInit {
public fruits = ["apple", "straw berry","orange","plum","grapes"].map( f => ({ name: f, like: false, dislike: false }));
check_box_type = CheckBoxType;
currentlyChecked: CheckBoxType;
constructor() { }
ngOnInit() {}
selectAllLike(){
this.fruits.forEach( f => {
f.like = true;
f.dislike = false;
})
}
}
<button (click)="selectAllLike()" >Like All</button>
<div *ngFor="let item of fruits; let i = index">
<p>{{item | json}}</p>
Like: <input type="checkbox" name="test" [(ngModel)]="item.like" [disabled]="item.dislike">
Dislike : <input type="checkbox" name="test" [(ngModel)]="item.dislike" [disabled]="item.like">
<hr>
</div>