2

I found this very nice directive on Medium (https://medium.com/@sub.metu/angular-fallback-for-broken-images-5cd05c470f08):

import {Directive, Input, HostBinding} from '@angular/core'
@Directive({
    selector: 'img[default]',
    host: {
      '(error)':'updateUrl()',
      '(load)': 'load()',
      '[src]':'src'
     }
  })

 export class ImagePreloadDirective {
    @Input() src:string;
    @Input() default:string;
    @HostBinding('class') className

    updateUrl() {
      this.src = this.default;
    }
    load(){
      this.className = 'image-loaded';
    }
  }

However, TSlint tells me I should use HostBinding instead of host on line 4. But I've found no documentation to help me implement this. Can someone help?

1 Answer 1

2

You can always configure tslint as you want:

tslint.json

...
"no-host-metadata-property": false,

If you want to follow Angular recommendations then you can rewrite it like:

image-preload.directive.ts

import { Directive, Input, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: 'img[default]',
})
export class ImagePreloadDirective {
  @Input()
  @HostBinding('src')
  src: string;

  @Input() default: string;

  @HostBinding('class') className;

  @HostListener('error')
  updateUrl() {
    this.src = this.default;
  }

  @HostListener('load')
  load() {
    this.className = 'image-loaded';
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I never knew that you could combine Input and Hostbinding, that's awesome.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.