Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

@Component({     selector: '.donation',     template: `     <figure id="donation" move>         <img src="image/qrcode.png"/>         <figcaption>         Buy me a cup of coffee.         </figcaption>     </figure>     ` }) export class DonationComponent{}  @Directive({     selector: '[move]' }) export class MoveDirective{}

Hey, I want to get the <figure id="donation"> element's width/height within MoveDirective and DonationComponent. I have read the documentation several times but still cannot find a way to this answer. Does somebody know this? Thanks a lot!

like image 961
胡亚雄 Avatar asked Oct 02 '16 02:10

胡亚雄


People also ask

How do you find the height and width of an element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.


1 Answers

You can use ElementRef as shown below,

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

import { Directive, Input, Output, 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.

like image 79
Nikhil Shah Avatar answered Sep 28 '22 14:09

Nikhil Shah