angular - Angular 5:如何从具有checked = true属性的数组中获取要在编辑组件上选中的复选框?
问题描述
我有一个从 API 服务调用的数据对象中检索的数组。我将一个选中的属性附加到该数组,以便在组件 ngOnInit() 中选择复选框。
我有一个主复选框列表,但只希望选择从服务调用返回的那些。
我尝试过使用一堆方法,包括数组上的 for 循环和 .forEach() 。
this.filterService.GetTierContent(this.config.id, "MCC").subscribe(data
=> {
data.forEach(i => this.selectedMcc.push({ type: "MCC", data: i.data,
checked: true }));
});
for(var i=0; i < this.selectedMcc.length; i++){
var index = this.selectedMcc.findIndex(i => i.data == i);
if(this.selectedMcc[index].checked === true) {
this.chk1 = true;
}
else {
this.chk1 = false;
}
}
<div *ngFor="let a of apparel; let i = index">
<mat-checkbox value="{{a.id}}" [(ngModel)] ="chk1"
(change)="onChecked(a, $event)">
{{a.mccCode}}
</mat-checkbox>
</div>
预期结果:
[(ngModel)]
将根据循环提供的内容保存一个true
或值。false
仅应在组件加载时检查从服务返回的数据数组(默认情况下)。
截至目前的实际结果:选中一个框,选中所有框。
解决方案
好的,那么这种方法呢?
// First of all, we set all checked-states to false in the apparel-list
this.apparel.forEach(element => {
element.checked = false;
});
// then we loop through the new list
this.selectedMcc.forEach( element => {
// if an element is checked, check its counterpart in the apparel-list
if (el.checked === true) {
this.apparel.filter(item => item.id === element.id)[0].checked = true;
}
});
// as result you should now have only those items from the incoming list selected
<div *ngFor="let a of apparel; let i = index">
<mat-checkbox
value="{{a.id}}"
[(ngModel)]="a.checked" // bind the checked-value of the item in the apparel-list
(change)="onChecked(a, $event)">
{{a.mccCode}}
</mat-checkbox>
</div>
PS:它假设服装列表中的元素也有一个 -checked
字段。
推荐阅读
- ios - 如何在 Swift 中使用 PDFKit 加粗选定的文本?
- python - python shuffle 矩阵中的列
- asp.net-mvc-5 - MVC 路由到内容以避免其他路由匹配?
- sql-server - BCP - 导出带有标题的 CSV
- python-3.x - 在一个线程中运行opencv,无法第二次启动
- python - Heroku Scheduler 中的 Redis Flushall 命令(Python/Django 项目)
- html - 如何在 2 个 div 之间添加 1 行并在 div 中很好地调整复选框?
- xamarin - 如何使用 Xamarin Forms 将 TextAlignment 绑定添加到模板?
- android - 跳过 Flutter 应用上的登录页面(Google + FireBase)
- uwp - 媒体播放器元素初始化后如何将焦点设置为播放/暂停按钮?