我有一个端点,为我返回一个图片网址。我想在一个组件中显示并在图像下面有一个标签来显示图像的尺寸。
我在下面编写了一个属性指令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 = {};
}
}
我的&#34; dimsGot&#34;我的组件中的方法没有输入,任何人都可以提出建议吗?
干杯
答案 0 :(得分:0)
怀疑它...我需要绑定到#34;加载&#34;元素事件(img)然后执行我的计算,并在我的指令中将结果发送到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;
}
}