In most cases, you can set the attribute directly.
Example:
<template>
<lightning-input type="checkbox" label="Demo" name="demo">
</lightning-input>
<lightning-button onclick={toggle} label="Toggle">
</lightning-button>
</template>
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
toggle() {
let el = this.template.querySelector('lightning-input');
el.checked = !el.checked;
}
}
Use setAttribute if you're exposing a property that should appear in the DOM.
// myComponent.js
import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement {
privateTitle;
@api
get title() {
return this.privateTitle;
}
set title(value) {
this.privateTitle = value.toUpperCase();
this.setAttribute('title', this.privateTitle);
}
}
This example causes the default "title" behavior to occur (display on mouse hover).
There's no need for setAttr, simply setting the properly directly works in most cases.