Angular6 如何在Angular 6指令中获得img.naturalWidth?

Angular6 如何在Angular 6指令中获得img.naturalWidth?,angular6,angular2-directives,Angular6,Angular2 Directives,我有一个自定义的Angular 6指令,如下所示: import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appImgOrientation]' }) export class ImgOrientationDirective { constructor(el: ElementRef) { console.log(el); console.log(el

我有一个自定义的Angular 6指令,如下所示:

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

@Directive({
  selector: '[appImgOrientation]'
})
export class ImgOrientationDirective {

  constructor(el: ElementRef) {   
      console.log(el);
      console.log(el.nativeElement);
  }

}
el
返回元素及其所有属性
el.nativeElement
具有许多属性。(50+)

但是
el.nativeElement
只返回元素html代码:

<img _ngcontent-c2 src="https://example.com/image.jpg" class="MyClass">

我想在指令中这样做。如何操作?

尽管登录el.nativeElement会将html标记打印到控制台,但该对象实际上具有可访问的属性,如下所示:

例如:

detectOrientation(imgUrl): void {
      var orientation;
      var img = new Image();
      img.src = imgUrl;

      img.onload = () => {
        if (img.naturalWidth > img.naturalHeight) {
          //landscape
          orientation = 'h';
        } else if (img.naturalWidth < img.naturalHeight) {
          // portrait
          orientation = 'v';
        } else {
          // even
          orientation = 'square';
        }
}

我也牵涉到同样的问题。el.nativeElement.naturalWidth将获得0,因为在ngafterViewInit(){}中运行代码时仍在加载img。必须等待img完成装载以获得其高度或宽度
console.log(el.nativeElement.naturalWidth);