简体   繁体   English

Angular 8 - 如何在衍生产品中使用 @HostBinding 而不是主机

[英]Angular 8 - How to use @HostBinding instead of host in a derivative

I found this very nice directive on Medium ( https://medium.com/@sub.metu/angular-fallback-for-broken-images-5cd05c470f08 ):我在 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.但是,TSlint 告诉我应该在第 4 行使用HostBinding而不是host 。但是我没有找到任何文档来帮助我实现这一点。 Can someone help?有人可以帮忙吗?

You can always configure tslint as you want:您可以随时根据需要配置 tslint:

tslint.json tslint.json

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

If you want to follow Angular recommendations then you can rewrite it like:如果你想遵循 Angular 的建议,那么你可以像这样重写它:

image-preload.directive.ts 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';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM