Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

clientWidth always returns zero on angular 9+

Hello I want to get width and height from image but clientWidth always returns zero, here is my directive

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);

  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you try using like this?

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) 
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...