Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

properties - Getting element height

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...