Salesforce LWC: Multi-Select pick-list using Lightning Web Component


In this blog we will learn about creating basic multi-select pick-list field using Lightning Web Component.
To implement multi-select pick-list we need a very basic UI with two standard lightning web component:

1. lightning-combobox
2. lightning-pill

We will use lightning-combobox to show all pick-list values and lightning-pill will help us to show selected pick-list values.
Lets go ahead and create basic HTML file:


<template>
    <div class="slds-p-around_xx-small">
        <lightning-combobox name="progress" label="Status" value={value} placeholder="Select Progress" 
        options={options} onchange={handleChange} ></lightning-combobox>
    </div>
    <div class="slds-p-around_xx-small">
        <template for:each={allValues} for:item="val">
            <lightning-pill key={val} label={val} name={val} onremove={handleRemove}></lightning-pill>
        </template>
    </div>
</template>

As you can see I am using lightning-combobox which is working like normal pick-list but my second part of UI will show you how many values you selected.
Lets go and see what logic we need in java script:


import { LightningElement, track } from 'lwc';

export default class MultiSelectPickListCmp extends LightningElement {
    @track value;
    @track options = [
        { label: 'New', value: 'new' },
        { label: 'In Progress', value: 'In Progress' },
        { label: 'Finished', value: 'Finished' },
    ];
    @track allValues = [];

    handleChange(event){
        if(!this.allValues.includes(event.target.value)){
            this.allValues.push(event.target.value);
        }
    }

    handleRemove(event){
        const valueRemoved = event.target.name;
        this.allValues.splice(this.allValues.indexOf(valueRemoved), 1);
    }
}

So in above java script we have two methods:

1. handleChange : This method is handling the change on pick-list field. If user is selecting any new value which is not selected before then we are adding that value to allValues list.

2. handleRemove: This method is removing selected values from allValues using basic method of Java Scripts.


Comments

Followers

Popular posts from this blog

Salesforce LWC: Multi-Record Creation using Lightning Web Component

Salesforce LWC: Basic Drag and Drop Functionality

Salesforce Lightning Web Component: Dynamic Column Selection in Lightning Datatable