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

时间:2017-03-06 17:39:23

标签: angular animation host

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

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

@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]': '',
   },
})

OR

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

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

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

2 个答案:

答案 0 :(得分:10)

官方指南是更喜欢HostListener / HostBinding

来自Angular style guide

  

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

     

样式06-03考虑优先选择@HostListener和@HostBinding   @Directive和@Component装饰器的主机属性。

     

在您的选择中保持一致。

     

为什么呢?与@HostBinding或方法关联的属性   与@HostListener关联的只能在单个中修改   放置在指令的类中。如果使用主机元数据属性,   你必须修改控制器内的属性声明,   以及与指令相关的元数据。

然而,angular / material2项目says to prefer "host"

  

主机绑定

     

首选使用指令配置中的主机对象而不是   @HostBinding和@HostListener。我们这样做是因为TypeScript   使用装饰器保存方法的类型信息,以及何时   该方法的一个参数是本机事件类型,这个   保留类型信息可能导致非浏览器中的运行时错误   环境(例如,服务器端预渲染)。

答案 1 :(得分:2)

两者都是等价的 在ES5中,装饰器不可用,您可以使用host: {}

相关问题