Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

primeng - Select only one checkbox item at a time

Is it possible to configure the primeng's checkbox module to behave as a selectbox, e.g. user can select only one checkbox at a time?

My component:

<div class="ui-g" style="width:250px;margin-bottom:10px">
    <div class="ui-g-12"><p-checkbox name="group1" value="New York" label="New York" [(ngModel)]="selectedCities" inputId="ny"></p-checkbox></div>
    <div class="ui-g-12"><p-checkbox name="group1" value="San Francisco" label="San Francisco" [(ngModel)]="selectedCities" inputId="sf"></p-checkbox></div>
    <div class="ui-g-12"><p-checkbox name="group1" value="Los Angeles" label="Los Angeles" [(ngModel)]="selectedCities" inputId="la"></p-checkbox></div>
</div>

Working stackblitz example.


1 Answers

I would suggest, that if you want a component that behaves like selectbox, use primeng's RadioButton component. On the other hand you can change the behavior of your chceckbox as well:

  • You need use the onChange() event on every checkbox component to know when user clicks on your checkbox.
  • After the user clicks to a checkbox, you need to store the current element. In your case it is the const latestCity = this.selectedCities[this.selectedCities.length - 1];. Since the checkbox items are stored as string values in an array, the current selected item is the last element of that array.
  • Lastly you need to empty the array and push the last selected item into that empty array:

    this.selectedCities.length = 0;

    this.selectedCities.push(latestCity);

Edited stackblitz.

like image 91
Runtime Terror Avatar answered Nov 03 '25 17:11

Runtime Terror



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!