Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string interpolation in style tag in Angular component?

@Component({
  selector: 'app-style',
  template: `
    <style>
      .test {
        color: {{ textColor }}
      }
    </style>
  `
})
export class StyleComponent {
  textColor = "red";
}

This doesn't seem to be working and I need my styles to be dynamic and in some specific CSS class. Is there some other way I could do this?

like image 302
S. Johnson Avatar asked May 05 '18 12:05

S. Johnson


1 Answers

When the component is renderd the style tag will move to head element of the page and any angular syntax inside this element will be ignored.

the only way I have found is to create the style element dynamic and provide the desire style.

app.component.ts

  textColor = 'red';
  constructor(private el: ElementRef) {

  }

  ngOnInit() {

    let style: string = `
     .test {color :${this.textColor}; }
    `;

    this.createStyle(style);

  }

  createStyle(style: string): void {
    const styleElement = document.createElement('style');
    styleElement.appendChild(document.createTextNode(style));
    this.el.nativeElement.appendChild(styleElement);
  }

app.template.html

<span class="test">test</span>

stackblitz demo

like image 181
Muhammed Albarmavi Avatar answered Sep 27 '22 21:09

Muhammed Albarmavi