2016-07-31 125 views
1

考慮這個孩子組件:Hostbinding ngIf在Angular2

@Component({ 
    selector: 'mySelector', 
    template: `<ion-spinner [ngIf]="ngif"></ion-spinner>` 
}) 


export class MyDirective { 

    ngif: boolean; 
    constructor() {} 

    @Input() serverWaiting:boolean = true; 
    @HostBinding('ngIf') 

    ngOnChanges() { 
     this.ngif = !this.serverWaiting ? true : null; 
    } 

主機組件的模板:

<mySelector [serverWaiting]></mySelector> 

主機部分:

@Component({ 
    templateUrl: 'hostComp.html', 
    directives: [myDirective] 
}) 

export class HostComp { 
    serverWaiting = true; 
} 

然而,沒有顯示的微調。任何想法我做錯了什麼?

來源:https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html

回答

4

@HostBinding('ngIf')裝飾需要與應約束和屬性值之前。

export class MyDirective { 
    constructor() {} 

    @HostBinding('ngIf') 
    ngif: boolean; 

    @Input() serverWaiting:boolean = true; 

    ngOnChanges() { 
     this.ngif = !this.serverWaiting ? true : null; 
    } 
} 

此代碼看起來並不有效

<mySelector [serverWaiting]></mySelector> 

[serverWaiting]顯示屬性的綁定,但不綁定的值。如果您期望,這不會分配true。您需要

<mySelector [serverWaiting]="true"></mySelector> 
+0

當使用'[ngIf] = 「ngIf」',我得到一個'myDirective - 聯模板:3:12 原始異常:無提供TemplateRef'!使用'* ngIf'可以消除錯誤,但仍然會一直顯示微調。 – nottinhill

+1

這可能是因爲命名屬性'ngIf'是一個壞主意。請改用一些不同的名字。 –

+2

嗨..現在即使命名實例成員'ngIf'也能工作。問題在'this.serverWaiting'之前是否定的,例如:this.ngif = this.serverWaiting? true:null;'。 – nottinhill