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
.
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.
@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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With