Another way of applying dynamic styling is using querySelector. A working example is here:- Playground
My html file looks like:-
<template>
<div data-id="divblock" class="navBar">
sanket
</div>
<lightning-button variant="brand" label="class 1"
title="Primary action" onclick={handleClick1}
class="slds-m-left_x-small"></lightning-button>
<lightning-button variant="brand" label="class 2"
title="Primary action" onclick={handleClick2}
class="slds-m-left_x-small"></lightning-button>
</template>
A data-id has been defined to div block to query using queySelctor in
JS file.There is two button to change the css class whenever it is
pressed.
And JS file looks like:-
handleClick1(){
console.log(this.template.querySelector('[data-id="divblock"]'));
if(this.template.querySelector('[data-id="divblock"]')){
this.template.querySelector('[data-id="divblock"]').className='class1';
}
}
handleClick2(){
console.log(this.template.querySelector('[data-id="divblock"]'));
if(this.template.querySelector('[data-id="divblock"]')){
this.template.querySelector('[data-id="divblock"]').className='class2';
}
}
Once button is clicked, I am accessing the element using querySelector
and pass the className from it.
My CSS file looks like:-
.class1 {
background-color: #e6e618;
}.class2 {
background-color: #df6e18;
}