Async HostBinding in directive

Tobias Bosch (member of the Angular team) writes:

Host bindings of a component ("child") are executed in the component that uses that component ("parent"). And the parent component can belong to a different NgModule. So if you use a pipe, the pipe is resolved against the NgModule of the parent component. However, if that NgModule does not declare the pipe that you are using, your component is broken.

This is the reason why we never wanted to have pipes in host bindings. After one of the bigger compiler refactorings before 2.0 final, we accidentally reintroduced it, but this was a bug, not a feature, as the semantics are wrong.

Source:

Async Host Binding No Longer Works #12671

There also is an open ticket to use Observables with HostBindings:

https://github.com/angular/angular/issues/19483


I'm sure there is no special way to do it. You need to explicitly assign to the property

@Directive({
    selector: 'img[my-directive]',
    host    : {
        '[alt]'  : "alt"
    }
})
export class MyDirective {
    altObservable: Observable<string>;
    alt: string;

    subscription:Subscription;    

    ngOnInit() {
      this.subscription = this.altObservable.subscribe(val => this.alt = val)
    }

    ngOnDestroy(){
      this.subscription && this.subscription.unsubscribe();
    }
}

Ensure you unsubscribe subscriptions you create imperatively.

Tags:

Angular