GoogleFont in LitElement ShadowDOM

122 views Asked by At

I'm creating a component in LitELement, with ShadowDOM, where I want to display an icon from GoogleFonts' Material Symbols Outlined.

In index.html, I am using this url:

https://fonts.googleapis.com/css2?family=Material+Symbols+Outline

as a regular css link:

<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet"/>

And it works fine when I drop something like

<span class="material-symbols-outlined">
  search
</span>

directly in index.html. But when I move it into the ShadowDOM component, it doesn't work. So, assuming that the index.html <link> has to stay in index.html in order to provide @font-face, I've tried to inject the stylesheet into the ShadowDOM to provide the class declaration (.material-symbols-outlined) - in three ways:

  1. Via css import:

    @customElement('my-comp')
    export class MyComponent extends LitElement {
      static styles = [
        css`
          @import url("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined");
        `
      ];
    
      render() {
        return html`
          <span class="material-symbols-outlined">search</span>
        `;
      }
    }
    
  2. Via link in render:

    @customElement('my-comp')
    export class MyComponent extends LitElement {
      render() {
        const iconsCssLink = html`
          <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet"/>
        `;
    
        return html`
          ${iconsCssLink}
          <span class="material-symbols-outlined">search</span>
        `;
      }
    }
    
  3. Via a shared component containing styles only:

     @customElement('icon-styles')
     export class IconStylesComponent extends LitElement {
       static styles = [
         css`
           @import url("https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined");
         `
       ];
     }
    

    and then importing it into the target component with ShadowDOM:

    @customElement('my-comp')
    export class MyComponent extends LitElement {
      static styles = [
        IconStylesComponent.styles,
      ];
    
      render() {
        return html`
          <span class="material-symbols-outlined">search</span>
        `;
      }
    }
    

None of these methods worked. Which piece of the puzzle am I missing?

1

There are 1 answers

0
HerberthObregon On

Just use @conectate/ct-icon

npm i @conectate/ct-icon

Usage

import { LitElement, html, css } from 'lit';
import '@conectate/ct-icon'

@customElement('Untitled-1')
export class UNtitled1 extends LitElement {
    static styles = [
        css`
            :host {
                display: block;
            }
        `
    ];

    render() {
        return html`<ct-icon icon="account"></ct-icon>`;
    }
}