I was curious if I can get element properties form component template. So I have made simple div with class and I've made this class:
export class viewApp{ elementView: any; viewHeight: number; myDOM: Object; constructor() { this.myDOM = new BrowserDomAdapter(); } clickMe(){ this.elementView = this.myDOM.query('div.view-main-screen'); this.viewHeight = this.myDOM.getStyle(this.elementView, 'height'); } }
getStyle()
, query()
are from BrowserDomAdapter. My problem is when I try to get height it is null
, but when I set some height by setStyle()
and then I get it by getStyle()
it returns proper value. After checking DOM and styles in browser I discovered that is because of two CSS elements. One is: .view-main-screen[_ngcontent-aer-1]{}
and second one is element{}
. .view-main-screen
has some stylings, but element is empty. When I add styles by setStyle()
it appears in element{}
. Why is that? How can I get element properties by using Angular2?
The offsetHeight property returns the viewable height of an element (in pixels), including padding, border and scrollbar, but not the margin. The offsetHeight property id read-only.
You can use 2 properties, clientHeight and offsetHeight to get the height of the div. clientHeight includes padding of the div. offsetHeight includes padding, scrollBar, and borders of the div.
height() It returns the current height of the element. It does not include the padding, border or margin. It always returns a unit-less pixel value. Note: The height() will always return the content height, regardless of the value of CSS box-sizing property.
To get an element's height with Vue. js, we can assign a ref to the element we want to get the height for. Then we can get the height with the clientHeight property of the element that's been assigned the ref. We assigned the ref with the ref prop set to a name.
The correct way is to use @ViewChild()
decorator:
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
Template:
<div class="view-main-screen" #mainScreen></div>
Component:
import { ElementRef, ViewChild } from '@angular/core'; export class viewApp{ @ViewChild('mainScreen') elementView: ElementRef; viewHeight: number; constructor() { } clickMe(){ this.viewHeight = this.elementView.nativeElement.offsetHeight; } }
That should do it but obviously you need to add your Component decorator.
Edit:
For Angular 8 or later you need to provide the 2nd parameter in ViewChild
@ViewChild('mainScreen', {read: ElementRef, static:false}) elementView: ElementRef;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With