Angular2

时间:2016-07-31 20:13:40

标签: angular

考虑这个子组件:

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

然而,Spinner没有出现。知道我做错了吗?

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

1 个答案:

答案 0 :(得分:6)

@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>