如何在Angular 6中没有* ngIf的情况下将异步管道的结果分配给变量 [英] How to assign result of async pipe to variable without *ngIf in Angular 6

查看:20
本文介绍了如何在Angular 6中没有* ngIf的情况下将异步管道的结果分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在没有 *ngIf 的情况下将 (areShipsExpanded$ | async) 赋值给变量?因为如果这是标志 true/false 当我有: *ngIf="(areShipsExpanded$ | async) as flag" 然后按钮在 false 的情况下不显示.

我想要这样的东西:

<button *let="(areShipsExpanded$ | async) 作为标志"(click)="expandAllShips(flag)">{{(flag ? "Collapse" : "Expand"}}

解决方案

参加聚会有点晚,但我从这个中等文章

您仍然使用 *ngIf,但您可以通过传入一个新对象并将您的可观察值作为属性来确保它始终评估为真.

<div *ngIf="{value1: myObs$ |async} as valuesObj">{{ valuesObject.value1 }}

IMO 这仍然有点笨拙,但比其他答案或创建自己的 *ngLet 指令要少得多.

正如文章中提到的,这也是将多个对象属性中的多个可观察值组合在一起的好方法,因此您不必有多个 async 语句或嵌套的 <;ng-container> 元素.

Is it possible to assign (areShipsExpanded$ | async) to variable without *ngIf? Because in case that this is flag true/false when I have: *ngIf="(areShipsExpanded$ | async) as flag" then button is not displaying in case of false.

And I would like something like this:

<button *let="(areShipsExpanded$ | async) as flag"
   (click)="expandAllShips(flag)">{{(flag ? "Collapse" : "Expand"}}
</button>

解决方案

Little late to the party here but I found a great example of how to do this from this medium article

You still use *ngIf but you make sure that it always evaluates truthy by passing in a new object with your observable value as a property.

<div *ngIf="{value1: myObs$ | async} as valuesObj">
    {{ valuesObject.value1 }}
</div>

IMO this is still a little hacky but much less hacky than the other answer or creating your own *ngLet directive.

As mentioned in the article, this is also a good way to group together multiple observable values in multiple object properties so you don't have to have multiple async statements or nested <ng-container> elements.

这篇关于如何在Angular 6中没有* ngIf的情况下将异步管道的结果分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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