1

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!

spoff
  • 13
  • 4
  • 1
    In what way is it broken? [quote from mdn](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments#notes): "_when using the – starball Aug 22 '22 at 18:20

1 Answers1

1

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>
    `;
  }
}
Augustine Kim
  • 841
  • 1
  • 5
  • thank you very much!!! It works ` :host { --color-black: red; --icon-my-cool-icon-name: "\u2295"; } ` – spoff Aug 23 '22 at 06:51