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

后端 未结 2 847
故里飘歌
故里飘歌 2021-02-02 09:34



        
2条回答
  •  旧时难觅i
    2021-02-02 09:39

    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.

提交回复
热议问题