2017-10-05 39 views
0

我有一個端點,爲我返回一個圖像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建議爲什麼?

乾杯

回答

0

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; 
     } 
     }