Pass value to lightning-input tag in LWC

lizalav picture lizalav · Feb 28, 2019 · Viewed 11.7k times · Source

Does anyone know how to pass checked value to checkbox in Lightning Web Component?

My code looks like:

and it doesn't work.

Answer

D Z picture D Z · Nov 25, 2019

The only way I have figured out how to do this is to add the checked attribute using JavaScript.

This example manually adds the checked attribute to the DOM element in the setter for isChecked.

JavaScript:

import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
    @track _isChecked = false;

    set isChecked(newValue) {
        this._isChecked = newValue;
        this.template.querySelector('lightning-input.cb').checked = newValue;
    }
    get isChecked() {
        return this._isChecked;
    }

    toggleChecked() {
        this.isChecked = !this.isChecked;
    }

    onChecboxChange(event) {
        this.isChecked = event.target.checked;
    }
}

HTML:

<template>
    <lightning-input class="cb" type="checkbox" label="my checkbox" onchange={onChecboxChange}></lightning-input>
    <br/>
    <lightning-button label="Toggle Checkbox" onclick={toggleChecked}></lightning-button>
    <br/>
    Checked Value: {isChecked}
</template>

Example in LWC Playground: https://developer.salesforce.com/docs/component-library/tools/playground/1wDdErq4X/31/edit

Another way to do this instead of using a setter is to use the renderedCallback() lifecycle hook to invoke something like this.template.querySelector('lightning-input.cb').checked = newValue; whenever the template renders/re-renders. However, you will need to ensure the variable tracking the checked state is actually bound to the template somewhere, or else the template may not re-render when the variable is changed.