【问题标题】:Angular 8 - How to use @HostBinding instead of host in a derivativeAngular 8 - 如何在派生中使用@HostBinding 而不是主机
【发布时间】:2020-02-01 02:15:53
【问题描述】:

我在 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';
    }
  }

但是,TSlint 告诉我应该在第 4 行使用 HostBinding 而不是 host。但我没有找到可以帮助我实现这一点的文档。有人可以帮忙吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以随时根据需要配置 tslint:

    tslint.json

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

    如果你想遵循 Angular 的建议,那么你可以像这样重写它:

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

    【讨论】:

    • 我从来不知道你可以结合输入和主机绑定,太棒了。
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2016-08-22
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2016-08-28
    相关资源
    最近更新 更多