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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With