简体   繁体   English

primeng - 一次只选择一个复选框项

[英]primeng - Select only one checkbox item at a time

Is it possible to configure the primeng's checkbox module to behave as a selectbox, eg user can select only one checkbox at a time? 是否可以将primeng的复选框模块配置为选择 ,例如,用户一次只能选择一个复选框?

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 . 工作stackblitz的例子

I would suggest, that if you want a component that behaves like selectbox, use primeng's RadioButton component. 我建议,如果你想要一个行为类似于selectbox的组件,请使用primeng的RadioButton组件。 On the other hand you can change the behavior of your chceckbox as well: 另一方面,您也可以更改chceckbox的行为:

  • You need use the onChange() event on every checkbox component to know when user clicks on your checkbox. 您需要在每个复选框组件上使用onChange()事件来了解用户何时单击您的复选框。
  • 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]; 在你的情况下,它是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 . 编辑stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM