Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style host element on Stencil component based on class

In Stencil when you have set shadow: true, styling the host element is as follows

:host {
    color: red;
}

This works. But now I have the following component

@Component({
    tag: 'my-component',
    styleUrl: 'my-component.scss',
    shadow: true
})
export class MyComponent {
    @Element() host: HTMLElement;

    render() {
        this.host.classList.add('is-test');
        return <div>Test</div>;
    }
}

in which I add the is-test class to the host element. Now, to apply styling based on that class I added the following

:host {
    color: red;

    &.is-test {
        background-color: green;
    }
}

I see is-test class on my-component element, but the background-color: green style is not applied. I must be doing something wrong here, any help would be appreciated!

like image 212
Jeanluca Scaljeri Avatar asked Jan 24 '20 15:01

Jeanluca Scaljeri


1 Answers

You can use :host():

:host {
    color: red;
}

:host(.is-test) {
    background-color: green;
}

By the way: If you want to set the class (or any attribute) on the host element, you can use the <Host> functional component:

import { Host } from '@stencil/core';

// ...

render() {
    return <Host class="is-test"><div>Test</div></Host>;
}
like image 59
Thomas Avatar answered Oct 17 '22 23:10

Thomas