我有一个端点,它为我返回一个图像url。我想在一个组件中显示,并在图像下面有一个标签来显示图像的尺寸。
我已经在下面编写了一个属性指令GetDimensionsDirective来完成此操作:
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 });
}
}在我的组件中也是这样使用的:
<img get-dimensions (calculatedDimensions)="dimsGot(event)" [src]="image.url" style="width:304px;height:228px;">在我的组件中,我有一个函数:
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“方法没有被输入,有人能告诉我为什么吗?
干杯
发布于 2017-10-05 21:51:32
找到了..。我需要绑定到元素(Img)的"load“事件,然后执行我的计算,并在EventEmitter中对结果进行emi,如下所示:
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 });
}
}然后,当我将标记连接到我的方法中的指令中来处理事件时,如下所示:
<img get-dimensions (calculatedDimensions)="dimsGot($event)" [src]="image.url">现在在我的组件代码中:
@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;
}
}https://stackoverflow.com/questions/46586370
复制相似问题