首页 > 解决方案 > 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仅应在组件加载时检查从服务返回的数据数组(默认情况下)。

截至目前的实际结果:选中一个框,选中所有框。

标签: angulartypescript

解决方案


好的,那么这种方法呢?

// 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字段。


推荐阅读