【问题标题】:Hostbinding ngIf in Angular2Angular2中的主机绑定ngIf
【发布时间】:2016-07-31 20:13:39
【问题描述】:

考虑这个子组件:

@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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    【讨论】:

    • 当使用[ngIf]="ngIf" 时,我得到一个myDirective - inline template:3:12 ORIGINAL EXCEPTION: No provider for TemplateRef!。使用*ngIf 可以消除错误,但仍然会一直显示微调器。
    • 这可能是因为将属性命名为ngIf 是个坏主意。请改用其他名称。
    • 嗨.. 即使将指令实例成员命名为 ngIf,现在也可以使用。问题是this.serverWaiting之前的否定,这样的作品:this.ngif = this.serverWaiting ? true : null;
    猜你喜欢
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2017-02-08
    相关资源
    最近更新 更多