1

I have a directive that can get the component is used on, via:

constructor(private el: ElementRef) {
    const element = this.el.nativeElement;
    /* Extra code */
}

Now I need to get the inhheirted final font-size, but trying to do:

fs = window.getComputedStyle(element).getPropertyValue('font-size');

or

fs = element.style.fontSize;

is not returning any value, just an empty string.

also, this question was for no help, as wrapping and injecting the window object lead to the same result

Is there a way to get the font size of the current component?

LeoGmz
  • 37
  • 1
  • 5

2 Answers2

1

it's important to note that the getComputedStyle method returns the computed style, which means that it computes the final style after taking into account any styles inherited from parent elements or styles applied through CSS rules. example:

constructor(private el: ElementRef) {
  const element = this.el.nativeElement;
  const computedStyle = getComputedStyle(element);
  const fontSize = computedStyle.getPropertyValue('font-size');
  console.log(fontSize);
}

If this still returns an empty string, make sure that the element actually has a font-size style applied to it. You can check the CSS styles applied to the element in your browser's developer tools.

Another thing to consider is that if the font size is set through a CSS class, you need to make sure that the class is applied to the native element before calling getComputedStyle.

MANITORATION
  • 557
  • 2
  • 5
  • 19
  • Thanks, I forgot to add that the component itself is not setting its font-size, it gets from a css – LeoGmz Mar 28 '23 at 10:33
  • The problem was setting the computed inside the constructor, as the component was not rendered, so no external styling were applied yet, moved it to ngAfterViewInit() – LeoGmz Mar 28 '23 at 11:07
0

You can access is directly from computedStyle like below.

getComputedStyle(element).fontSize

if style is added as inline then below should work

element.style.fontSize

Ariel
  • 69
  • 5