Angular img upload directive

I am trying to make a simple directive. When the image is loaded the img src will be set to the line box @Input()

. On load, the image will be set to its original src value (or at least the way I'm trying to implement it).

I used the answer here: https://stackoverflow.com/a/1645076/ ... but is not a directive and hence will require a few changes everywhere I use images.

My first try:

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;
  }

}

      

from

 <img src="{{hero.imgUrl}}" alt="Random first slide">

      

in

<img src="{{hero.imgUrl}}" alt="Random first slide" [tohLoadingImg]="'/assets/ring.svg'">

      

Mistake:

Can't bind to 'tohLoadingImg' since it isn't a known property of 'img'. (".imgUrl}}" alt="Random first slide">-->

      

What am I missing?

0


source to share


1 answer


Thanks @Aravind for the direction. This is how I solved it (using a component, not a directive):

Hot-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() { }

}

      

kok-img.component.html:



<div [class]="imgContainerClass">
  <img *ngIf="loading" src="{{spinnerSrc}}" alt="loading"/>
  <img [hidden]="loading" (load)="onLoad()" src="{{imgSrc}}" alt="Hero Pic"/>
</div>

      

And when using:

 <toh-spinner-img [imgSrc]="hero.imgUrl" [spinnerSrc]="'/assets/ring.svg'"></toh-spinner-img>

      

0


source







All Articles