[英]Angular - How can I check a checkbox based on values in Array?
我有一个带有这些复选框的表单,以允许用户 select 一个项目的多个“口径”:
这些复选框是通过 ngFor 从一个名为“calibres”的数组中创建的,该数组具有所有可能的值,如下面的代码所示:
组件.html
<div >
<mat-checkbox #checkBox
*ngFor="let calibre of calibres; let i = index"
[value]="calibre"
(change)="getCheckbox()"
class="example-margin mb-0 mt-1" >{{calibre}}</mat-checkbox>
</div>
component.ts上的 getCheckbox () function 创建在我的复选框中选中的那些元素的数组
getCheckbox() {
this.item.calibres = [];
const checked = this.checkBox.filter(checkbox => checkbox.checked);
checked.forEach(data => {
this.item.calibres.push ( data.value );
});
}
当我提交表单时,这个检查过的元素数组存储在后端,用于表单创建的这个特定“项目”,所以存储的数组将类似于 [50,60]。 仅选中复选框。
我试图做的是在填写表单时(出于“编辑”项目的目的)检查存储在数组中的那些复选框。
我怎样才能做到这一点?
希望这对将来的人有所帮助,
我通过属性绑定和一个小的 function 以一种简单的方式解决了这个问题。
问题:我有一个数组Ex: Categories = ["a","d"]
,它的值只有选中的复选框,当用户想要编辑它时,我必须再次显示复选框,并且复选框已经选中。
解决方案:
在 HTML 文件中 - 使用与 function 的属性绑定来检查该值是否存在于数组中并返回真或假。 (您也可以使用 *ngFor)
<h3>Category</h3>
<label><input type="checkbox" [checked]="checkCat('a')">a</label>
<label><input type="checkbox" [checked]="checkCat('b')">b</label>
<label><input type="checkbox" [checked]="checkCat('c')">c</label>
<label><input type="checkbox" [checked]="checkCat('d')">d</label>
在.ts文件里面
cat = ["a","d"]; // checkbox data received from backend
checkCat(data){
let ref = this.cat.find(x => x == data); // this checks the cat[] array
if(ref == data){
return true;
} else {
return false;
}
}
如果您使用的是 model,那么这将非常简单和干净。
假设您的口径低于 model
calibres = [
{value: 1, isSelected: false},
{value: 5, isSelected: false},
{value: 4, isSelected: false}
];
当您从后端获取数组时,只需检查
backendArray = [2,4];
还有一个 function 在您获取数据后检查 isSelected 标志
this.calibres = this.calibres.map(
(elem) =>{ elem.isSelected = this.backendArray.indexOf(elem.value) != -1 ? true : false;
return elem});
HTML 部分使用选中的属性。 在更改时传递口径并将切换逻辑执行到 isSelected 标志
<div >
<mat-checkbox #checkBox
*ngFor="let calibre of calibres"
[checked]="calibre.isSelected"
[value]="calibre.value"
(change)="getCheckbox(calibre)"
class="example-margin mb-0 mt-1" >{{calibre.value}}</mat-checkbox>
</div>
你不能在循环中使用属性[checked]=true
。 因为您为数组中的项目创建了复选框,这些项目由 ischecked 属性过滤。 因此,使用此属性将完成您的工作
<mat-checkbox #checkBox
*ngFor="let calibre of calibres; let i = index"
[value]="calibre"
[checked]="true"
(change)="getCheckbox()"
class="example-margin mb-0 mt-1" >{{calibre}}</mat-checkbox>
更新:
getCheckbox() {
this.item.calibres = this.checkBox.map(checkbox => {
return {
value: checkbox.value,
isChecked: checkbox.checked
};
});
}
<mat-checkbox #checkBox
*ngFor="let calibre of calibres; let i = index"
[value]="calibre.value"
[checked]="calibre.isChecked"
(change)="getCheckbox()"
class="example-margin mb-0 mt-1" >{{calibre.value}}</mat-checkbox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.