Angular 2 : @HostBinding or host: {}?

标签 angular animation host

我想知道在使用组件的 @HostBindinghost 属性之间是否存在巨大差异(如果存在,差异是什么?)?

我在使用动画时一直在问自己这个问题,因为我在这些情况下(看起来很接近):

@Component({
  selector: 'mycomponent',
  animations: [
    trigger('myTransition', [
      state('inactive', style({
      backgroundColor: '#eee',
      transform: 'scale(1)'
    })),
    state('active',   style({
      backgroundColor: '#cfd8dc',
      transform: 'scale(1.1)'
    })),
    transition('inactive => active', animate('100ms ease-in')),
    transition('active => inactive', animate('100ms ease-out'))
  ])],
  host: {
    '[@myTransition]': '',
   },
})

@Component({
  selector: 'mycomponent',
  animations: [
    trigger('myTransition', [
      state('inactive', style({
      backgroundColor: '#eee',
      transform: 'scale(1)'
    })),
    state('active',   style({
      backgroundColor: '#cfd8dc',
      transform: 'scale(1.1)'
    })),
    transition('inactive => active', animate('100ms ease-in')),
    transition('active => inactive', animate('100ms ease-out'))
  ])],
})

export class MyComponent {
  @HostBinding('@myTransition') get myTransition() {
    return '';
  }
}

然后我认为这可能是一种新的主​​机绑定(bind)方式。

提前感谢您的建议和意见;)

最佳答案

官方给出的指导是更喜欢HostListener/HostBinding

来自 Angular style guide

HostListener/HostBinding decorators versus host metadata

Style 06-03 Consider preferring the @HostListener and @HostBinding to the host property of the @Directive and @Component decorators.

Do be consistent in your choice.

Why? The property associated with @HostBinding or the method associated with @HostListener can be modified only in a single place—in the directive's class. If you use the host metadata property, you must modify both the property declaration inside the controller, and the metadata associated with the directive.

但是,angular/material2 项目 says to prefer "host"

Host bindings

Prefer using the host object in the directive configuration instead of @HostBinding and @HostListener. We do this because TypeScript preserves the type information of methods with decorators, and when one of the arguments for the method is a native Event type, this preserved type information can lead to runtime errors in non-browser environments (e.g., server-side pre-rendering).

关于 Angular 2 : @HostBinding or host: {}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632114/

相关文章:

javascript - JQuery 动画在第一次点击时移动,但在第二次点击时不移动

javascript - 如何按特定属性对 JSON 进行排序以将其显示在 Angular 数据表中

angular - 如何检测 Angular 2 中的任何按键?

css - 设计登录 css Ionic

c++ - WIN32, C++ : Is it possible to animate a window without hiding it?

CSS3 幻灯片动画问题

qt - 动态更改 QML 映射中 osm 插件的自定义主机 URL

node.js - 为 node.js Web 服务应用程序安装服务器

css - 动态改变 chartjs 的高度

c++ - Qt or general c++ 如何在c++中获取或检测<a href ="file.html">的主机