1

I'm new to Angular (and Angular 5.x specifically), and am hoping someone can shed some light on something for me..

I'm trying to figure out how to read (not manipulate) the CSS style properties of a certain class that's applied to a known element.

For example, I've got a text element that has the "special-fancy-text" CSS class applied to it. How can I access that element's CSS class's properties to dynamically tell what font family, font size, color, or other options are currently set within it?

Thanks!

Rick
  • 245
  • 3
  • 13

1 Answers1

2

You can use ViewChild like this:

html

<div  #filterDiv class='col-md-2' style='color: blue'>Filter by:</div>

Component

  @ViewChild('filterDiv') filterDivRef: ElementRef;

  ngAfterViewInit(): void {
    if (this.filterDivRef.nativeElement) {
      console.log(this.filterDivRef.nativeElement.style.color);
    }
  }

The above will display 'blue' to the console. This this for more details: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

Though I don't think that if you use a style class that this will be able to tell you the style properties from that class.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • Yeah, that only seems to give me inline styles. If I knew the name of the CSS class being applied, is there an easy way to read its properties? Oh, and just wanted to say thanks for doing the tutorials on PluralSite - I've been working through them - good stuff! – Rick Jan 31 '18 at 17:14
  • 1
    Thanks! :-) The only thing I saw to read stylesheet info was on the `document` object ... which I have not used from Angular. Here is a link: https://stackoverflow.com/questions/324486/how-do-you-read-css-rule-values-with-javascript ... but notice that this is not Angular. Considering the lack of other responses here ... I'm not sure there is an easy way. – DeborahK Jan 31 '18 at 17:51