【问题标题】:Angular2: @HostBinding or host: {}?Angular2:@HostBinding 还是主机:{}?
【发布时间】:2017-07-26 16:56:29
【问题描述】:

我想知道使用组件的@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 '';
  }
}

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

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

【问题讨论】:

    标签: angular animation host


    【解决方案1】:

    两者是等价的。
    在没有装饰器的 ES5 中,可以使用host: {}

    【讨论】:

    • 好吧,这只是使用主机绑定的另一种方式,就像输入:[] 和 @Input?
    • 是的,装饰器可用的所有东西都可以在host 中使用,反之亦然。
    • 它们真的是等价的吗?我目前遇到的问题是它们会导致不同的行为。 host 有效,而 @HostBinding 无效。我实际上想要类似的东西 -> github.com/angular/angular/blob/… 尽管有指导方针,但即使有角度使用主机也很有趣
    • 是的,它们是等价的。可能值得在 StackBlitz 或类似的仓库中提出一个新问题。
    • 我添加了问题 -> stackoverflow.com/questions/50942849/… 会对为什么观察到这种行为非常感兴趣
    【解决方案2】:

    官方指导是首选HostListener/HostBinding

    来自Angular style guide

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

    样式 06-03 考虑更喜欢 @HostListener 和 @HostBinding @Directive 和 @Component 装饰器的主机属性。

    在您的选择上保持一致。

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

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

    主机绑定

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

    【讨论】:

    • 我也注意到了这个矛盾
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2011-01-26
    • 2018-02-25
    相关资源
    最近更新 更多