Getting element height

前端 未结 3 951
逝去的感伤
逝去的感伤 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:43

    update2

    constructor(private elementRef:ElementRef) {}
    
    someMethod() {
       console.log(this.elementRef.nativeElement.offsetHeight);
    }
    

    Accessing nativeElement directly is discouraged but current Angular doesn't provide other ways as far as I know.

    update

    https://github.com/angular/angular/pull/8452#issuecomment-220460761

    mhevery commented 12 days ago We have decided to remove Ruler service, and so it is not part of the public API.

    original

    As far as I know the Ruler class should provide that functionality https://github.com/angular/angular/blob/master/modules/angular2/src/platform/browser/ruler.ts if this isn't enought you probably need to access elementRef.nativeElement and use direct DOM access and functions provided by the elements.

    new Ruler(DOM).measure(this.elRef).then((rect: any) => {
    });
    

    Rules service is safe in WebWorker. See also the comments on https://github.com/angular/angular/issues/6515#issuecomment-173353649

    0 讨论(0)
  • 2020-12-09 03:47
    <div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>
    
    itemClick(dom){
      var height=dom.clientHeight;
      // ...
    }
    
    0 讨论(0)
  • 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:

    <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;
    
    0 讨论(0)
提交回复
热议问题