HTML上的Angular 6别名 [英] Angular 6 alias on HTML

查看:55
本文介绍了HTML上的Angular 6别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在HTML中使用某个元素,然后再用角度6一次,我想将该元素另存为别名,但是如果指令或元素不是 * ngIf .

I need to use some element in HTML with angular 6 more then once and I want to save that element as alias, but I can't do that if the directive or element isn't *ngIf.

假设我有此代码-

<dumb-comp
    [name]="(someObservable | async).name"
    [role]="(someObservable | async).role"
    [age]="(someObservable | async).age">
</dumb-comp>

我每次都必须使用异步管道...我想将(someObservable | async)保留在别名上,并在每次需要的时候使用它...是否有解决方案??

I have to use async pipe each time... I want to keep (someObservable | async) on an alias and use it every time that I need ... is there any solution for that?

我想在没有 * ngIf 的情况下使用它,我想知道为什么为什么仅使用 * ngIf .

I want to use that without *ngIf, and I want to know please why is that possibly only using *ngIf.

我知道我可以将所有数据传递给dumb-comp,但我想先过滤数据.这里的代码只是一个更大问题的示例

推荐答案

这是一个缺少且要求很高的功能的角度.不幸的是,他们不是很渴望添加它.但是,您可以创建自己的自定义指令并使用它.但是,与本机的角度模板语法相比,此方法的效果较差.

It's a missing and highly requested feature of angular. Unfortunately they are not very eager to add it. You can however create your own custom directive and use it. However this will perform poorly compared to a native angular template syntax.

对于 * ngLet 示例,您可以检查

For an *ngLet example, you can check this implementation of ngrx.

如果添加了此内容,则可以将模板更改为此:

If you've added this, you can change your template to this:

<dumb-comp *ngLet="someObservable | async as res"
  [name]="res?.name"
  [role]="res?.role"
  [age]="res?.age">
</dumb-comp>

如前所述,这将导致 res undefined/null ,而等待可观察对象的解析.

As mentioned, this will cause the res to be undefined/null while waiting for the observable to resolve.

如果您担心多个订阅,则可以使用 share()运算符.这将在订阅者之间共享订阅,然后您可以根据需要(尽可能多地使用)使用 async 管道,而不会对性能产生任何严重影响

If multiple subscriptions are your worry, you can use the share() operator. This will share the subscription amongst the subscribers, then you can use the async pipe as much as you want (on that observable) without any serious performance impact

这篇关于HTML上的Angular 6别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆