首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试使用Directive获取图像尺寸

尝试使用Directive获取图像尺寸
EN

Stack Overflow用户
提问于 2017-10-05 21:05:14
回答 1查看 393关注 0票数 0

我有一个端点,它为我返回一个图像url。我想在一个组件中显示,并在图像下面有一个标签来显示图像的尺寸。

我已经在下面编写了一个属性指令GetDimensionsDirective来完成此操作:

代码语言:javascript
复制
import { Directive, Input, Output, ElementRef, Renderer, EventEmitter } from '@angular/core';

@Directive({
    selector: "[get-dimensions]"
})

export class GetDimensionDirective {
    @Output() calculatedDimensions = new EventEmitter<any>();

    constructor(private el: ElementRef) {
        this.getDimensions();
    }
    getDimensions() {
        this.calculatedDimensions.emit({ "height": this.el.nativeElement.offsetHeight, "width": this.el.nativeElement.offsetWidth });
    }
}

在我的组件中也是这样使用的:

代码语言:javascript
复制
<img get-dimensions (calculatedDimensions)="dimsGot(event)" [src]="image.url" style="width:304px;height:228px;">

在我的组件中,我有一个函数:

代码语言:javascript
复制
import { GetDimensionDirective } from './../../../../shared/directives/get-dimesions';
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'my-image',
  templateUrl: './image.component.html',
  styleUrls: ['./image.component.css']
})
export class ImageComponent implements OnInit {
  image={url: "http://localhost/myApi.WebService/api/resource/12", dimensions:null};


  constructor() { }

  ngOnInit() {
  }

  dimsGot(dimensions) {
    this.image.dimensions = {};
  }
}

我的组件中的"dimsGot“方法没有被输入,有人能告诉我为什么吗?

干杯

EN

回答 1

Stack Overflow用户

发布于 2017-10-05 21:51:32

找到了..。我需要绑定到元素(Img)的"load“事件,然后执行我的计算,并在EventEmitter中对结果进行emi,如下所示:

代码语言:javascript
复制
import { Directive, Input, Output, ElementRef, Renderer, EventEmitter } from '@angular/core';

@Directive({
    selector: "[get-dimensions]",
    host: {
        '(load)': 'getDimensions()'
      }    
})

export class GetDimensionDirective {
    @Output() calculatedDimensions = new EventEmitter<any>();

    constructor(private el: ElementRef) {
    }
    getDimensions() {
        this.calculatedDimensions.emit({ "height": this.el.nativeElement.offsetHeight, "width": this.el.nativeElement.offsetWidth });
    }
}

然后,当我将标记连接到我的方法中的指令中来处理事件时,如下所示:

代码语言:javascript
复制
<img get-dimensions (calculatedDimensions)="dimsGot($event)" [src]="image.url">

现在在我的组件代码中:

代码语言:javascript
复制
@Component({
  selector: 'my-image',
  templateUrl: './image.component.html',
  styleUrls: ['./image.component.css']
})
export class ImageComponent implements OnInit {
  image = { url: "myApi.WebService/api/resource/12", dimensions: { height: 0, width: 0 } };
.
.
.
.
      dimsGot(dims) {
        if (this.image && dims) {
          this.image.dimensions.height = dims.height;
          this.image.dimensions.width = dims.width;
        }
      }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46586370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档