Angular2:@HostBinding或主持人:{}?

nic*_*ere 10 animation host angular

我想知道在使用@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]': '',
   },
})
Run Code Online (Sandbox Code Playgroud)

要么

@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 '';
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我认为它可能是主机绑定的新方式.

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

Rip*_*ess 13

官方指南是首选HostListener/HostBinding

来自Angular风格指南

HostListener/HostBinding装饰器与主机元数据

样式06-03考虑将@HostListener和@HostBinding放在@Directive和@Component装饰器的host属性上.

在你的选择中保持一致.

为什么?与@HostBinding关联的属性或与@HostListener关联的方法只能在指令的类中的单个位置进行修改.如果使用主机元数据属性,则必须同时修改控制器内的属性声明以及与该指令关联的元数据.

然而,angular/material2项目表示更喜欢"主机"

主机绑定

首选在指令配置中使用host对象而不是@HostBinding和@HostListener.我们这样做是因为TypeScript保留了带有装饰器的方法的类型信息,并且当该方法的一个参数是本机事件类型时,这种保留的类型信息可能导致非浏览器环境中的运行时错误(例如,服务器端预先-rendering).