2016-08-04 73 views
13

(Angular 2 RC4)如何使用@HostBinding和Angular 2中的@Input屬性?

隨着@HostBinding我們應該能夠修改主機的屬性,對吧?我的問題是,這是否也適用於@Input()屬性,如果是這樣,什麼是正確的用法?如果沒有,是否有另一種方法來實現這一目標?

我做了一個Plunker這裏來說明我的問題:https://embed.plnkr.co/kQEKbT/

假設我有一個自定義組件:

@Component({ 
    selector: 'custom-img', 
    template: ` 
    <img src="{{src}}"> 
    ` 
}) 
export class CustomImgComponent { 
    @Input() src: string; 
} 

我想src屬性與屬性指令飼料:

@Directive({ 
    selector: '[srcKey]' 
}) 
export class SrcKeyDirective implements OnChanges { 

    @Input() srcKey: string; 
    @HostBinding() src; 

    ngOnChanges() { 
    this.src = `https://www.google.com.mt/images/branding/googlelogo/2x/${this.srcKey}_color_272x92dp.png`; 
    } 
} 

爲什麼不能更改自定義組件的[src]輸入屬性?

@Component({ 
    selector: 'my-app', 
    directives: [CustomImgComponent, SrcKeyDirective], 
    template: `<custom-img [srcKey]="imageKey"></custom-img>` 
}) 
export class AppComponent { 
    imageKey = "googlelogo"; 
} 

謝謝!

回答

4

@HostBinding()不創建屬性綁定到主機組件的屬性。這可能是值得一個錯誤報告雖然;-)

我得到它的解決方法與exportAs和模板變量,但這是相當醜陋的工作。 https://plnkr.co/edit/TobNVn?p=preview

經過一番考慮後,我認爲它應該起作用。否則,我不知道@HostBinding() src;會做什麼。

@HostBinding('attr.src') src;@HostBinding('class.src') src;是更常見的情況。

+1

謝謝你的快速反應。我在這裏發佈了一個錯誤報告:https://github.com/angular/angular/issues/10499 – Laurens

28

您需要的裝飾結合起來是這樣的:

@HostBinding('class.active') @Input() active: boolean = false;

+1

如果我的輸入是一個對象並且我想綁定這個對象的屬性,我該怎麼辦? –

+0

@hugoderhungrige你碰巧解決了這個問題嗎?如何做一個對象的屬性主機綁定... –

+0

@RobertKoritnik檢查我的答案,它允許你使用一個對象的屬性 – SystemR

0

如果您@input是一個對象,你可以這樣做:

@Input() settings: Settings; 

@HostBinding('class.active') 
public get isActive(): boolean { 
    return this.settings.isActive; 
} 
相關問題