2017-03-06 65 views
2

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

我當時以爲是我的可能是主機綁定的新方式。

在此先感謝您的建議和意見;)

回答

2

兩者都是等效的。
在ES5其中裝飾不可用,則可以使用host: {}

+1

好吧,所以它只是另一種使用主機綁定的方式,就像輸入:[]和@Input? – nicolasrigaudiere

+0

是的,裝飾器可用的所有東西都可以在'host'中找到,反之亦然。 –

4

官方的指導是從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

我也注意到了這個矛盾 –

相關問題