ROBO-KY
ROBO-KY

Reputation: 37

primeng single select checkbox console error

I have multiple checkboxes and when I click on one checkbox - other must be unselected and when I click on the same checkbox - this checkbox must be unselected as well. Right now I have this implementation:

In html page I'm using *ngFor like this:

<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>

And in my component I have this:

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

public selectedValue;

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

Everything works fine, but there is an error in the console when I click on selected checkbox:

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)

What am I doing wrong? Thanks!

Upvotes: 0

Views: 4029

Answers (2)

xxxception
xxxception

Reputation: 955

As alternative solution can use binary option, see "Boolean value" section. It allows selecting a boolean value instead of multiple values.
Thus in your case, the checkbox should look like this:

<p-checkbox  [binary]="true" (onChange)="changeValue(item.value)"  [(ngModel)]="selectedValue" name="test" value="{{item.value}}" [inputId]="item.value"></p-checkbox>

Upvotes: 2

Arun
Arun

Reputation: 508

As per requirement edit changeValue function to this

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

In PrimeNg p-checkBox ngModel property refers to an array to bind the selected values.

Upvotes: 3

Related Questions