0

html file:

<div #sampleComponent class="cdt-sample-component"
[ngStyle]="{'height': (view_height) + 'px'}" >
  <app-component></app-component>
</div>

css file:

.cdt-sample-component {
    display: flex;
    flex: 1;
    height: calc(100% / 3);
}

}

ts file:

constructor(private renderer: Renderer2) {
}

ngAfterViewInit() {
    logger.info("NativeElement height " + this.renderer.selectRootElement(this.metricsComponent['nativeElement']).getAttribute('height'));
    }

The above log print in ts file is returning null for "height" attribute. I am using angular 7.

I would like to get the value of "height" attribute defined in css in div element "cdt-sample-component", somehow i am getting null. Can you please answer on how to get the height attribute value in ts file which is defined in css file.

vrreddy1234
  • 343
  • 5
  • 16

1 Answers1

0

You could try to use ViewChild to get a reference to the element and read it's clientHeight or offsetHeight property.

Controller

import { AfterViewInit, Component, ElementRef, ViewChild } from "@angular/core";

export class SomeComponent implements AfterViewInit {
  @ViewChild("sampleComponent") sampleComponent: ElementRef<any>;

  ngAfterViewInit() {
    console.log(this.sampleComponent.nativeElement.clientHeight);
  }
}

For clientHeight vs offsetHeight see here: https://stackoverflow.com/a/15615701/6513921

ruth
  • 29,535
  • 4
  • 30
  • 57
  • Thanks a lot for immediate response. I am able to see the clientHeight value in ts file. I am curious to know if there is a way to get or access any css property value in ts file, just an example, if i have "height1" property in css file: – vrreddy1234 Apr 01 '21 at 07:21
  • @vrreddy1234: You could probably use `getComputedStyle()`. See here: https://stackoverflow.com/a/6338234/6513921 – ruth Apr 01 '21 at 12:41
  • What if the markup is still not loaded into DOM, I just want to get some CSS property for selector in my Angular code? – Alexander May 15 '22 at 16:05
  • @Alexander: If the markup isn't loaded in the DOM yet, then this method cannot be used as the template reference variable would be unavailable for the `@ViewChild()` to find. – ruth May 16 '22 at 07:01
  • @ruth yeap, i understand. I was planning to find CSS property selector from one of numerous CSS files that are loaded. But seems like this is too complex: I would need to check ALL loaded stylesheets in the query result. – Alexander May 16 '22 at 07:12
  • 1
    @Alexander: That could be quite tricky. An inefficient suggestion: [`getComputedStyle(document.body)`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle). Then try the [methods](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration#methods) from the returned `CSSStyleDeclaration` object. – ruth May 16 '22 at 08:01