【问题标题】:clientWidth always returns zero on angular 9+clientWidth 在角度 9+ 上始终返回零
【发布时间】:2020-12-30 13:48:35
【问题描述】:

您好,我想从图像中获取宽度和高度,但 clientWidth 总是返回零,这是我的指令

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

@Directive({
  selector: '[image-fit]'
})
export class ImageFitDirective {

  constructor(
    private _elementRef: ElementRef
  ) {
  }

  ngAfterViewInit(): void {
    this._fit();

  }

  private _fit(): void {
    let width: any = this._elementRef.nativeElement.clientWidth;
    let height: any = this._elementRef.nativeElement.clientHeight;

    // console.log(this._elementRef);
    console.log(width, height);

  }

}

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    你可以试试这样使用吗?

    import { Directive, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[image-fit]',  
      host: {
        '(click)':"_fit()"
      }
    })
    export class ImageFitDirective {
    
      constructor(
        private _elementRef: ElementRef
      ) { }
    
      ngAfterViewInit(): void {
        this._fit()
      }
    
      _fit(): void {
        const width = this._elementRef.nativeElement.offsetWidth;
        const height = this._elementRef.nativeElement.offsetHeight;
        console.log('width', width)
        console.log('height', height) 
      }
    
    }
    

    【讨论】:

    • 好的,但是当您点击父组件时仍然无法工作?
    【解决方案2】:

    来自docs in developer.mozilla

    对于内联元素,Element.clientWidth 属性为零,并且 没有 CSS 的元素;否则,它是元素的内部宽度 像素。它包括填充,但不包括边框、边距和 垂直滚动条(如果存在)。

    你可以使用 getBoundingClientRect()

    private _fit(): void {
        const  rect=this._elementRef.nativeElement.getBoundingClientRect()
        let width: any = rect.width;
        let height: any = rect.height;
    
        console.log(width, height);
    
      }
    

    顺便说一句,如果你想应用到 img,你应该使用事件 load 否则给出值 0 除非图像被浏览器“缓存”

    <img [src]="'https://picsum.photos/200/300?random=1'" 
         (load)="onLoad($event.target)" >
    
    onLoad(img:any)
    {
       console.log(img.clientWidth,img.getBoundingClientRect())
    }
    

    更新一如既往,如果我们在一个带有 *ngIf 之类的 div 下有一些,例如

    <div *ngIf="condicion">
      ..what ever...
    </div>
    

    我们做不到

    //this NOT WORK
    condition=true;
    myImageFitDirective._fit()
    

    因为当我们调用函数_fit() 时,Angular 没有“重绘”。我们需要用 setTimeout 括起来

    //now is OK
    condition=true;
    setTimeout(()=>{
       myImageFitDirective._fit()
    })
    

    【讨论】:

    • _fit() 仍然返回零 :( 登录后
    • 真的我不知道会发生什么-好吧,您忘记在指令中写implements AfterViewInit-但我不知道您写问题时是否是拼写错误-。顺便说一句,我在答案中添加了一个更新,以考虑“*ngIf 的问题”(我不知道是不是你的情况)
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多