angular - using async pipe on observable<Object> and bind it to local variable in html

筅森魡賤 提交于 2019-11-28 17:29:38

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

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

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>

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>

Or a space for primitive value,

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

@Bjorn Schijff and @estus

Instead of:

<div *ngIf="(user$ | async) || {}; let user">

Do:

<div *ngIf="(user | async) as user">

Use following syntax:

<div *ngIf="(user | async) as user"> 

Note: The addition of “as user” at the end of the expression.

What this will do is wait until user$ | async has evaluated, and bind the result to the value of user (non-dollar-suffixed).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!