Getting element height

前端 未结 3 985
逝去的感伤
逝去的感伤 2020-12-09 02:58

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:



        
3条回答
  •  庸人自扰
    2020-12-09 03:49

    The correct way is to use @ViewChild() decorator:

    https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

    Template:

    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;
    

提交回复
热议问题