jcdsr
jcdsr

Reputation: 1151

directive hoslistener to image tag with load event - angular4

I'm trying to get a directive using hostlistener to detect when images are completed loaded with angular4

    <img imgDirective src="124.jpg">

    @HostListener('load', ['$event.target']) 
    public onLoad(event) {
        this.img = false;
    }

Then if the load is complete I output the value using an EventEmitter, however, the hostlistener event seems not working at all. Does any one knows why?if I a change the event on the hostlistener as below? the event works, but not for image tag. Do you know if this is possible?

    @HostListener('window:load', ['$event.target']) 
    public onLoad(event) {
        this.img = false;
    } 

I got the event form https://developer.mozilla.org/en-US/docs/Web/Events

What events can we use in angular4? is a limited list?

Upvotes: 1

Views: 5546

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657268

I would do it this way:

@Directive({
  selector: '[imgDirective]',
})
class ImgDirective {
  @Input() imgDirective:string;

  constructor(private element:ElementRef){
    element.nativeElement.src = 'resources/spinner.png';
  } 

  @HostListener('load', ['$event'])
  onLoad() {
    this.element.nativeElement.src = this.imgDirective;
  }
}

and use it like

<img [imgDirective]="124.jpg">

Upvotes: 2

Related Questions