Angular2:@HostBinding或主机:{}?

问题描述:

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

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

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

我当时以为是我的可能是主机绑定的新方式。

在此先感谢您的建议和意见;)

两者都是等效的。
在ES5其中装饰不可用,则可以使用host: {}

+1

好吧,所以它只是另一种使用主机绑定的方式,就像输入:[]和@Input? – nicolasrigaudiere

+0

是的,装饰器可用的所有东西都可以在'host'中找到,反之亦然。 –

官方的指导是从Angular style guide

HostListener喜欢HostListener/HostBinding

/HostBinding装饰抗宿主元

风格06-03考虑更喜欢@HostListener和@HostBinding到 @Directive和@Component de的主机属性corators。

请确保您的选择一致。

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

然而,角度/材料2项目says to prefer "host"

主机绑定

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

+0

我也注意到了这个矛盾 –