bixi
Version:
企业级中后台前端解决方案
62 lines (49 loc) • 1.7 kB
text/typescript
import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
export class SafeSrcDirective implements OnInit, OnChanges, OnDestroy {
src = '';
bixiSafeSrc: string;
bixiErrorClass = 'bixi-safe-src-error';
bixiSuccessClass = 'bixi-safe-src-success';
bixiErrorSrc: string;
subscription = new Subscription();
constructor(
private el: ElementRef,
private renderer: Renderer2
) {
}
ngOnInit() {
this.setSrc(this.bixiSafeSrc);
this.watchError();
}
ngOnChanges(changes: SimpleChanges) {
const srcChange = changes.bixiSafeSrc;
if (srcChange.firstChange) return;
this.setSrc(this.bixiSafeSrc);
}
setSrc(src: string) {
if (!src) return;
if (this.src === src) return;
this.src = src;
this.renderer.setAttribute(this.el.nativeElement, 'src', src);
}
watchError() {
this.subscription.add(fromEvent(this.el.nativeElement, 'error').subscribe(() => {
this.setSrc(this.bixiErrorSrc);
this.renderer.addClass(this.el.nativeElement, this.bixiErrorClass);
this.renderer.removeClass(this.el.nativeElement, this.bixiSuccessClass);
}));
this.subscription.add(fromEvent(this.el.nativeElement, 'load').subscribe(() => {
if (this.src === this.bixiErrorSrc) return;
this.renderer.addClass(this.el.nativeElement, this.bixiSuccessClass);
this.renderer.removeClass(this.el.nativeElement, this.bixiErrorClass);
}));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}