LitElement rendering. The result is broken due to comments

Viewed 51

Here is my custom element and than you can see on the screenshot the comments that break the styles

@customElement('icon-icon')
export class Icon extends LitElement {
  @property({type: String}) 
  icon='';
  @property({type: String}) 
  color='';
  
  static get styles() {
    return css`
    .icon {
      color: var(--icon-color);      
    }
    .icon::after {
      content: var(--icon-content);
    }
    `;
  }
  
  render() {
    return html`
    <style>
      :host {
        --icon-content: var(--icon-${this.icon});
        --icon-color: var(--color-${this.color});
      }
    </style>
    <i class="icon"></i>
    `;
  }
}

dev tools screenshot

Does somebody has any idea? Thanx!

1 Answers

The comments are there due to the template expressions but it should apply the correct styles regardless.

If you're not seeing their effects, make sure --icon-my-cool-icon-name and --color-black are both set. Maybe you want to provide some default value too.

If you want to avoid using the <style> tag, you can also do this.style.setProperty('--icon-content', `var(--icon-${this.icon})`) in a lifecycle, maybe updated?

import type {PropertyValues} from 'lit';

@customElement('icon-icon')
export class Icon extends LitElement {
  @property({type: String}) 
  icon='';
  @property({type: String}) 
  color='';
  
  static get styles() {
    return css`
    .icon {
      color: var(--icon-color);      
    }
    .icon::after {
      content: var(--icon-content);
    }
    `;
  }

  updated(changedProperties: PropertyValues<this>) {
    if (changedProperties.has('icon')) {
      this.style.setProperty('--icon-content', `var(--icon-${this.icon})`);
    }
    if (changedProperties.has('color')) {
      this.style.setProperty('--icon-color', `var(--color-${this.color})`);
    }
  }
  
  render() {
    return html`
    <i class="icon"></i>
    `;
  }
}
Related