How to get element's width/height within directives and component?

胡亚雄 picture 胡亚雄 · Oct 2, 2016 · Viewed 106.9k times · Source

Hey,I want to get element's width/height within MoveDirective and DonationComponent,I read the document several times but still can not find a way to this answer.Do somebody know this please help me,thanks a lot!

Answer

micronyks picture micronyks · Oct 2, 2016

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.