简体   繁体   English

指令中的异步主机绑定

[英]Async HostBinding in directive

I'm looking for the best way to handle HostBinding with async value.我正在寻找使用异步值处理 HostBinding 的最佳方法。

Before Angular v2.1.2 I could use the host property in the @Directive decorator like that :在 Angular v2.1.2之前,我可以像这样在@Directive装饰器中使用host属性:

@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.但看起来这不是预期的行为,因为版本 2.1.2 修复了它。 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 .现在,当使用 AoT 编译进行编译时,我得到Parser Error: Host binding expression cannot contain pipes in Directive

Tobias Bosch (member of the Angular team) writes: Tobias Bosch(Angular 团队成员)写道:

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.并且父组件可以属于不同的 NgModule。 So if you use a pipe, the pipe is resolved against the NgModule of the parent component.因此,如果您使用管道,管道将根据父组件的 NgModule 进行解析。 However, if that NgModule does not declare the pipe that you are using, your component is broken.但是,如果该 NgModule 未声明您正在使用的管道,则您的组件已损坏。

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.在 2.0 final 之前的一次更大的编译器重构之后,我们不小心重新引入了它,但这是一个错误,而不是一个功能,因为语义是错误的。

Source:来源:

Async Host Binding No Longer Works #12671 异步主机绑定不再有效 #12671

There also is an open ticket to use Observables with HostBindings:还有一个公开的票证可以将 Observables 与 HostBindings 一起使用:

https://github.com/angular/angular/issues/19483 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.确保取消订阅您强制创建的订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM