Angular img 加载指令 [英] Angular img loading directive

查看:20
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆