Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hostbinding ngIf in Angular2

Tags:

angular

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

like image 853
stevek-pro Avatar asked Jul 31 '16 20:07

stevek-pro


People also ask

What is the difference between HostBinding and HostListener?

Introduction. @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.

What is the HostBinding?

HostBindinglinkDecorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.

What is the use of @HostListener?

HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

What does @HostBinding do in Angular?

HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive. @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.


1 Answers

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>
like image 200
Günter Zöchbauer Avatar answered Oct 11 '22 01:10

Günter Zöchbauer