首页 > 解决方案 > primeng 单选复选框控制台错误

问题描述

我有多个复选框,当我单击一个复选框时 - 必须取消选中另一个复选框,当我单击同一个复选框时 - 此复选框也必须取消选中。现在我有这个实现:

在 html 页面中,我使用 *ngFor 如下:

<ng-container *ngFor="let item of items">
<div>
    <p-checkbox (onChange)="changeValue(item.value)"  [(ngModel)]="selectedValue" name="test" value="{{item.value}}" [inputId]="item.value"></p-checkbox>
    <label [for]="item.value">{{item.label}}</label>
</div>
</ng-container>

在我的组件中,我有这个:

public items: any[] = [
    { label: 'labelOne', value: true },
    { label: 'labelTwo', value: false }
]

public selectedValue;

public changeValue(value) { 
   this.selectedValue = value; 
}

一切正常,但是当我单击选中的复选框时,控制台中出现错误:

Checkbox.html:7 ERROR TypeError: this.model.filter is not a function
at Checkbox.push../node_modules/primeng/fesm5/primeng-checkbox.js.Checkbox.removeValue (primeng-checkbox.js:87)
at Checkbox.push../node_modules/primeng/fesm5/primeng-checkbox.js.Checkbox.updateModel (primeng-checkbox.js:62)
at Checkbox.push../node_modules/primeng/fesm5/primeng-checkbox.js.Checkbox.onClick (primeng-checkbox.js:52)
at Object.eval [as handleEvent] (Checkbox.html:7)
at handleEvent (core.js:29239)
at callWithDebugContext (core.js:30309)
at Object.debugHandleEvent [as handleEvent] (core.js:30036)
at dispatchEvent (core.js:19859)
at core.js:28448
at HTMLDivElement.<anonymous> (platform-browser.js:1032)

我究竟做错了什么?谢谢!

标签: angulartypescriptprimeng

解决方案


根据要求编辑changeValue函数到这个

changeValue(value) { 
  if(this.selectedValue.length === 2) {
    this.selectedValue = [value]; //as selectedValue is array
  } 
}

在 PrimeNg p-checkBox中,ngModel 属性是指一个数组来绑定选定的值。


推荐阅读