Angular2中的主机绑定ngIf

mes*_*lds 3 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;
    }
Run Code Online (Sandbox Code Playgroud)

主机组件的模板:

 <mySelector [serverWaiting]></mySelector>
Run Code Online (Sandbox Code Playgroud)

主机组件:

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

export class HostComp {
    serverWaiting = true;
}
Run Code Online (Sandbox Code Playgroud)

然而,Spinner没有显示.知道我做错了什么吗?

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

Gün*_*uer 7

@HostBinding('ngIf')装饰需要与应约束和属性值之前.

export class MyDirective {
    constructor() {}

    @HostBinding('ngIf')
    ngif: boolean;

    @Input() serverWaiting:boolean = true;

    ngOnChanges() {
        this.ngif = !this.serverWaiting ? true : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码看起来不合适

<mySelector [serverWaiting]></mySelector>
Run Code Online (Sandbox Code Playgroud)

[serverWaiting]表示属性绑定但不绑定值.true如果你期望的话,这不会分配.你需要

<mySelector [serverWaiting]="true"></mySelector>
Run Code Online (Sandbox Code Playgroud)

  • 嗨..现在甚至可以命名指令实例成员`ngIf`.问题是以前`this.serverWaiting`,这样的作品否定:`this.ngif = this.serverWaiting?true:null;`. (2认同)