Search code examples
javascriptcssangularangular-reactive-formscss-variables

Angular component: change css variable for application but not component itself


I have an application that uses css variables for most styling, such as font-size.

:root {
  --font_size_base: 16px;
}
body {
  font-size: var(--font_size_base);
}

I need to create a component that change change that root variable and increase font size but I need the font size inside that component to remain constant.

In the component I have an HTML input type range:

  ngAfterContentInit() {
    this.form.valueChanges.subscribe((value) => {
      if (value.fontSize) {
        this.document.documentElement.style.setProperty(
          '--font_size_base',
          `${value.fontSize}px`
        );
      }
    });
  }

This does change the font size, but it of course also affects the fonts inside the component. I need to define a font size inside the component and have it not be affected. I can prevent this with CSS changes by setting view encapsulation to shadowdom, but this is not CSS but a style tag on the body tag directly, so it still affect my component.

I tried assigning a value inside the component's CSS but it did not work

:host {
  --font_size_base: 12;
}

Is this even possible? Here's a stackblitz of the situation: https://stackblitz.com/edit/angular-ivy-hghqm3?file=src/app/controller/controller.component.css


Solution

  • You can directly set a font size for you component, like that:

    :host {
      font-size: 12px;
    }
    

    or

    :host {
      --font_size_base: 12px;
      font-size: var(--font_size_base);
    }