试图获得图像尺寸与指令
问题描述:
我有一个端点,为我返回一个图像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;">
,并在我的conponent我具备的功能:
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”方法没有被输入,可以任何e建议为什么?
干杯
答
Sussed ......我需要绑定到元素(IMG)的“load”事件thenperform我的计算和EMI的结果EventEmitter像这样在我的指令:
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;
}
}