Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async HostBinding in directive

Tags:

angular

I'm looking for the best way to handle HostBinding with async value.

Before Angular v2.1.2 I could use the host property in the @Directive decorator like that :

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

But it looks like this was not the intended behavior, since version 2.1.2 fixes it. See don't access view local variables nor pipes in host expressions.

Now, when compiling with AoT compilation, I get Parser Error: Host binding expression cannot contain pipes in Directive.

like image 487
Noémi Salaün Avatar asked Nov 07 '16 10:11

Noémi Salaün


People also ask

What is difference between HostListener and HostBinding?

HostListener listens to host events, while HostBinding allows us to bind to a property of the host element. The host is an element on which we attach our component or directive. This feature allows us to manipulate the host styles or take some action whenever the user performs some action on the host element.

What is the purpose of @HostBinding?

@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 host binding in angular 8?

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

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

like image 78
Sander_P Avatar answered Sep 21 '22 23:09

Sander_P