我正在尝试制作一个简单的指令。加载图像时,img src将设置为@Input()
字符串字段。在加载时,图像将被设置为原始的src值(或者至少我试图实现它的方式)。
我在这里使用答案: https://stackoverflow.com/a/38837619/843443 但它不是一个指令,因此无论我在哪里使用图像都需要进行一些更改。
我的第一次尝试:
放入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">-->
我错过了什么?
答案 0 :(得分:0)
感谢@Aravind的指导。这就是我解决它的方法(通过使用组件而不是指令):
的旋img.component.ts:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'toh-spinner-img',
templateUrl: './spinner-img.component.html',
styleUrls: ['./spinner-img.component.scss']
})
export class SpinnerImgComponent implements OnInit {
@Input() imgSrc: String;
@Input() spinnerSrc: String;
@Input() imgContainerClass: String;
loading: boolean = true
onLoad() {
this.loading = false;
}
constructor() { }
ngOnInit() { }
}
的旋img.component.html:
<div [class]="imgContainerClass">
<img *ngIf="loading" src="{{spinnerSrc}}" alt="loading"/>
<img [hidden]="loading" (load)="onLoad()" src="{{imgSrc}}" alt="Hero Pic"/>
</div>
并在使用中:
<toh-spinner-img [imgSrc]="hero.imgUrl" [spinnerSrc]="'/assets/ring.svg'"></toh-spinner-img>
答案 1 :(得分:0)
尝试一下
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">