|
| 1 | +import {Component, Input, HostBinding, ViewChild, ElementRef} from 'angular2/core'; |
| 2 | + |
| 3 | +import {isPresent} from '../../util/util'; |
| 4 | + |
| 5 | + |
| 6 | +@Component({ |
| 7 | + selector: 'ion-img', |
| 8 | + template: |
| 9 | + '<div *ngIf="_useA" class="img-placeholder" [style.height]="_h" [style.width]="_w"></div>' + |
| 10 | + '<img #imgA *ngIf="_useA" (load)="_onLoad()" [src]="_srcA" [style.height]="_h" [style.width]="_w">' + |
| 11 | + '<div *ngIf="!_useA" class="img-placeholder" [style.height]="_h" [style.width]="_w"></div>' + |
| 12 | + '<img #imgB *ngIf="!_useA" (load)="_onLoad()" [src]="_srcB" [style.height]="_h" [style.width]="_w">' |
| 13 | +}) |
| 14 | +export class Img { |
| 15 | + private _src: string = ''; |
| 16 | + private _srcA: string = ''; |
| 17 | + private _srcB: string = ''; |
| 18 | + private _useA: boolean = true; |
| 19 | + private _w: string; |
| 20 | + private _h: string; |
| 21 | + private _enabled: boolean = true; |
| 22 | + |
| 23 | + constructor(private _elementRef: ElementRef) {} |
| 24 | + |
| 25 | + @ViewChild('imgA') private _imgA: ElementRef; |
| 26 | + @ViewChild('imgB') private _imgB: ElementRef; |
| 27 | + |
| 28 | + @Input() |
| 29 | + set src(val: string) { |
| 30 | + val = (isPresent(val) ? val : ''); |
| 31 | + |
| 32 | + if (this._src !== val) { |
| 33 | + this._src = val; |
| 34 | + this._loaded = false; |
| 35 | + this._srcA = this._srcB = ''; |
| 36 | + this._useA = !this._useA; |
| 37 | + this._update(); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private _update() { |
| 42 | + if (this._enabled) { |
| 43 | + if (this._useA) { |
| 44 | + this._srcA = this._src; |
| 45 | + |
| 46 | + } else { |
| 47 | + this._srcB = this._src; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + enable(shouldEnable: boolean) { |
| 53 | + this._enabled = shouldEnable; |
| 54 | + this._update(); |
| 55 | + } |
| 56 | + |
| 57 | + @HostBinding('class.img-loaded') |
| 58 | + private _loaded: boolean = false; |
| 59 | + |
| 60 | + private _onLoad() { |
| 61 | + this._loaded = this.isLoaded(); |
| 62 | + } |
| 63 | + |
| 64 | + isLoaded() { |
| 65 | + let imgEle: HTMLImageElement; |
| 66 | + |
| 67 | + if (this._useA && this._imgA) { |
| 68 | + imgEle = this._imgA.nativeElement; |
| 69 | + |
| 70 | + } else if (this._imgB) { |
| 71 | + imgEle = this._imgB.nativeElement; |
| 72 | + |
| 73 | + } |
| 74 | + return (imgEle && imgEle.src !== '' && imgEle.complete); |
| 75 | + } |
| 76 | + |
| 77 | + @Input() |
| 78 | + set width(val: string | number) { |
| 79 | + this._w = (typeof val === 'number') ? val + 'px' : val; |
| 80 | + } |
| 81 | + |
| 82 | + @Input() |
| 83 | + set height(val: string | number) { |
| 84 | + this._h = (typeof val === 'number') ? val + 'px' : val; |
| 85 | + } |
| 86 | + |
| 87 | +} |
0 commit comments