Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - Async HostBinding in directive

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...