2

I'm trying work out a way to use jss in an angular 6 project to allow dynamic styling of components.

The issue I'm running into is that the dynamic styles are always less specific than the predefined styles, because the dynamic styles are missing the attribute selector from the view encapsulation system.

I can easily get the raw CSS output from jss, but I haven't been able to find a way to run this through the angular compiler to have the selectors modified to include the attribute selector.

Ideally I'd like to be able to bind a <style> tag in the template to a cssText property of the component, but this doesn't seem possible.

import {Component, OnInit} from '@angular/core';
import * as color from 'color';
import jss from 'jss';

@Component({
  selector: 'app-example',
  template: `
    <p [ngClass]="cssClasses">TEST TEST</p>
  `,
  styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit {
  cssClasses: { [name: string]: boolean } = {};

  constructor() {
  }

  ngOnInit() {
    const {classes} = jss.createStyleSheet({
      dynamicClass: {
        color: color('blue').hex(),
      }
    }).attach();

    this.cssClasses[classes.dynamicClass] = true;
  }

}

example.component.scss

p {
    color: 'red'
}

result

If there a way of invoking the angular CSS compiler on an arbitrary piece of CSS, with the context of a particular component?

Or another way to achieve what I'm describing above?

Note: I'm aware that I can bind and apply inline styles to elements, but this doesn't meet my requirements - in particular you cannot target pseudo selectors, or do media queries etc using this mechanism.

I could probably work around this by not using the scss file at all and defining all default styles through the jss mechanism however I would prefer to retain the ability to use the normal style system so that the jss is only used where needed. Also I think I would still run into selectivity issues when styling 3rd party components using jss.

Michael
  • 2,189
  • 16
  • 23
  • An answer to this question could be applicable to https://stackoverflow.com/questions/52730731/changing-style-class-attributes-dynamically-in-angular-6 as well. – Michael Oct 14 '18 at 14:52

0 Answers0