Angular img加载指令 [英] Angular img loading directive
本文介绍了Angular img加载指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制定一个简单的指令.加载图像时,img src将设置为@Input()
字符串字段.在加载时,图像将被设置为原始src值(或至少是我尝试实现它的方式).
I am trying to make a simple directive. When the image is loading, the img src will be set to an @Input()
string field. On load, the image will be set to the original src value (or at least how I am trying to implement it).
我在这里使用答案: https://stackoverflow.com/a/38837619/843443 但这不是指令,因此无论我在哪里使用图片,都需要进行很多更改.
I was using the answer here: https://stackoverflow.com/a/38837619/843443 but is isn't a directive, and thus would require a number of changes wherever I use images.
我的第一次尝试:
loading-img.directive.ts:
loading-img.directive.ts:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[tohLoadingImg]'
})
export class LoadingImgDirective {
imgSrc: String;
@Input()
spinnerSrc: String;
constructor(private el: ElementRef) {
this.imgSrc = el.nativeElement.src;
el.nativeElement.src = this.spinnerSrc;
}
@HostListener('load') onLoad() {
this.el.nativeElement.src = this.imgSrc;
}
}
来自:
<img src="{{hero.imgUrl}}" alt="Random first slide">
收件人:
<img src="{{hero.imgUrl}}" alt="Random first slide" [tohLoadingImg]="'/assets/ring.svg'">
错误:
Can't bind to 'tohLoadingImg' since it isn't a known property of 'img'. (".imgUrl}}" alt="Random first slide">-->
我想念什么?
推荐答案
尝试一下
import {
Directive,
Attribute,
Renderer2,
ElementRef,
HostListener } from '@angular/core';
@Directive({
selector: '[uiImageLoader]'
})
export class UiImageLoaderDirective {
constructor(
@Attribute('loader') public loader: string,
@Attribute('onErrorSrc') public onErrorSrc: string,
private renderer: Renderer2,
private el: ElementRef) {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.loader);
}
@HostListener('load') onLoad() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.el.nativeElement.src);
}
@HostListener('error') onError() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.onErrorSrc);
}
}
用法
<img
uiImageLoader
onErrorSrc="/assets/images/no-available-800.png"
loader="/assets/images/image-loader.svg"
[src]="post.imagePath" [alt]="post.title">
这篇关于Angular img加载指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文