5

Consider this Child Component:

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

The Host Component's Template:

 <mySelector [serverWaiting]></mySelector>

The Host Component:

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

export class HostComp {
    serverWaiting = true;
}

Yet, the Spinner is not shown. Any idea what I am doing wrong?

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

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147

1 Answers1

7

The @HostBinding('ngIf') decorator needs to be before the property with the value that should be bound.

export class MyDirective {
    constructor() {}

    @HostBinding('ngIf')
    ngif: boolean;

    @Input() serverWaiting:boolean = true;

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

This code doesn't look valid

<mySelector [serverWaiting]></mySelector>

[serverWaiting] indicates property binding but doesn't bind a value. This doesn't assign true in case you expect that. You would need

<mySelector [serverWaiting]="true"></mySelector>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • When using `[ngIf]="ngIf"`, I am getting a `myDirective - inline template:3:12 ORIGINAL EXCEPTION: No provider for TemplateRef!`. Using `*ngIf` gets rid of the error, but still the spinner is shown all the time. – Stephan Kristyn Aug 01 '16 at 12:35
  • 1
    That's probably because naming a property `ngIf` is a bad idea. Please use some different name instead. – Günter Zöchbauer Aug 01 '16 at 12:47
  • 2
    Hi.. works now even with naming the directive instance member `ngIf`. Problem was negation before `this.serverWaiting`, such works: `this.ngif = this.serverWaiting ? true : null;`. – Stephan Kristyn Aug 01 '16 at 12:53