角度的-在可观察的< Object>上使用异步管道并将其绑定到html中的局部变量 [英] angular - using async pipe on observable<Object> and bind it to local variable in html

查看:66
本文介绍了角度的-在可观察的< Object>上使用异步管道并将其绑定到html中的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可观察到的用户$,它具有很多属性(名称,标题,地址...)

Hi I have a observable user$ with a lot of properties (name, title, address...)

component{
  user$:Observerable<User>;
  constructor(private userService:UserService){
    this.user$ = this.userService.someMethodReturningObservable$()
  }
}

是否可以使用html模板中的异步管道来订阅它并将其绑定到这样的局部变量

Is there a way to use the async pipe in the html template to subscribe to it and bind it to a local variable like this

<div #user="user$ | async">
  <h3> {{user.name}}
</div>

我知道可以在构造函数中订阅它,然后在OnLeave/OnDestroy中取消订阅,但我只是好奇是否可以使用异步管道.

I know can can subscribe to it in the constructor and then unsubscribe in OnLeave/OnDestroy but I was just curious if I could use the async pipe.

欢呼

推荐答案

#

# is template reference variable. It defers to DOM element and cannot be used like that.

到目前为止,本地变量尚未在Angular中实现,此已解决的问题可以会被监控以获取相关问题的引用.

Local variables aren't implemented in Angular as of now, this closed issue can be monitored for the references to related issues.

自Angular 4起,ngIfngFor指令的语法已更新,以允许使用局部变量.有关详细信息,请参见 ngIf参考.因此可以做

Since Angular 4 the syntax of ngIf and ngFor directives was updated to allow local variables. See ngIf reference for details. So it is possible to do

<div *ngIf="user$ | async; let user">
  <h3> {{user.name}}
</div>

这将创建div包装器元素并为其提供隐藏行为,因此无需?.'Elvis'运算符.

This will create div wrapper element and will provide cloaking behaviour to it, so there's no need for ?. 'Elvis' operator.

如果不需要额外的标记,可以将其更改为

If no extra markup is desirable, it can be changed to

<ng-container *ngIf="user$ | async; let user">...</ng-container>

如果不希望使用伪装行为,则可以将表达式更改为真实的占位符值.

If cloaking behaviour is not desirable, the expression can be changed to truthy placeholder value.

占位符可以是空的对象值

A placeholder can be empty object for object value,

<div *ngIf="(user$ | async) || {}; let user">
  <h3> {{user?.name}}
</div>

或原始值的空格,

<div *ngIf="(primitive$ | async) || ' '; let primitive">
  <h3> {{primitive}}
</div>

这篇关于角度的-在可观察的&lt; Object&gt;上使用异步管道并将其绑定到html中的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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