Is there any way to dynamically pass a value to attributes in css fie in lwc?
You could pass the class name dynamically to the HTML element based on a attribute/property:
MyComponent.html
<div class={navBar}>
MyComponent.js
get tabNavBarClass() {
return this.navBar ? 'navBar1' : 'navBar2';
}
MyComponent.css
.navBar2 {
height:29px;
}
.navBar2:before {
background: red;
}
.navBar1 {
height:29px;
}
.navBar1:before {
background: blue;
}
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;
}