Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value to lightning-input tag in LWC

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

My code looks like:

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

    constructor() {
        super();
        isChecked = false;
    }   

}
<template>
    <lightning-card title="My Card" icon-name="custom:custom9">
        <div class="slds-m-around_medium">
                <lightning-input type="checkbox" label="my checkbox" name="input1" checked="{isChecked}"></lightning-input>
        </div>
    </lightning-card>    
</template>

and it doesn't work.

like image 487
lizalav Avatar asked Mar 05 '23 10:03

lizalav


1 Answers

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.

like image 179
D Z Avatar answered Mar 15 '23 07:03

D Z