根据动态生成的输入的条件设置复选框值



在我的角度应用程序中,我正在尝试实现产品之间的比较功能。我有一个产品列表,每个产品都有一个复选框。最初,所有复选框都将被取消选中。当我单击产品的复选框时,我正在检查要比较的所选产品总数是否不大于 2。如果大于 2,则该复选框应变为未选中状态。我尝试使用以下代码但没有成功。非常感谢对此的任何帮助。

.HTML:

 <div *ngFor="let att of displayProduct ">
   {{att.productName}}
   <input type="checkbox" name="att.productId" value="compare" 
   (change)="checkBoxClicked(att.productId)"
   [checked]= "test(att.productId)"> Compare
 </div>

TS:

compareList: string = [];
checkBoxClicked(val: string){
    if (this.compareList.length<2){
    this.compareList.push(val);
    }
    this.test(val);
}
test(val: string){
if (_.find(this.compareList, function(data ){return data == val }) === undefined){
    return false;
    }
    else {
    return true;
    }
}

html:

  <div *ngFor="let att of displayProduct ">
   {{att}}
   <input type="checkbox" name="att" value="compare" 
   (change)="checkBoxClicked($event, att)"> Compare
 </div>

TS:

checkBoxClicked(e, value: string){
    if (this.compareList.length<2 && e.currentTarget.checked){     
        this.compareList.push(value); //adding checked value to the list     
    }
    else  if(!e.currentTarget.checked){
        var index = this.compareList.indexOf(value);
        if (index > -1) {
            this.compareList.splice(index, 1); //removing when unchecked
        }
      }
    else  
      e.currentTarget.checked = false;  //not selecting if list length > 2  
  }

请找到内联评论。

随着 Angular 的更新,它为我们提供了许多新功能。 您可以使用 mat 组件来执行这些类型的操作,它们是专门为此设计的。

请找到以下示例:

网页代码

  <mat-list>
    <mat-list-item id="columnInfo" *ngFor="let att of displayProduct">
      <mat-checkbox (click)="$event.stopPropagation()" 
        (change)="$event ? prodSelection.toggle(att.id) : null" 
        [checked]="prodSelection.isSelected(att.productId)">
        {{ att.productName }}
      </mat-checkbox>
    </mat-list-item>
  </mat-list>         

对于 TS 文件,您可以使用 SelectionModel 一个专门为此类操作设计的类。将全局变量创建为选择内容:

  prodSelection = new SelectionModel<string>(true, []);

并在 HTML 中引用它,正如我在示例中提到的。请参阅此链接垫复选框以获取进一步说明。

最新更新