lightning-dual-listbox is used to show two side-by-side listboxes. This component can be used to show list of available options and selected options.
Recently my team got requirement where selected options should not be removed but we can select new options. Ex.. If user already selected Option1, Option2 then they should not remove these options but they add and remove other options like option3, option4.
Let us see how we can accomplish this in lightning web component.
We can use onchange event to set default values if those values are de-selected. value property will show selected values. We will set this property with default selected values.
Here is code which show toast message that you can deselect those values and then set it default selected values.
handleChange(event)
{
var selectedRows=event.detail.value;
if(this.defaultValues!=undefined && this.defaultValues!=null && this.defaultValues.length>0)
{
var items=this.defaultValues.filter(value => selectedRows.includes(value));
if(this.defaultValues.length!==items.length)
{
this.showMessage('Notification','Existing selected value(s) can not be removed','error');
this.defaultValues=[...this.defaultValues];
event.preventDefault();
return;
}
}
}
Complete Code:
Test Page: