简体   繁体   English

如何使用角度的异步管道检查 *ngIf 内的长度?

[英]How to check length inside *ngIf with async pipe in angular?

How to check length inside *ngIf with async pipe?如何使用异步管道检查*ngIf内的长度?

I try to do this way, but its not working.我尝试这样做,但它不起作用。 what is the correct way to do it?正确的做法是什么?

<mat-menu #favoriteMenu="matMenu">
  <ng-container *ngIf="items$ | async as items && items.length; else empty">
    <button mat-menu-item *ngFor="let item of items">
      ...
    </button>
  </ng-container>
  <ng-template #empty>no favorite here</ng-template>
</mat-menu>

I think the best solution still is, to split this up into 2 containers.我认为最好的解决方案仍然是将其分成 2 个容器。 That is not pretty, but AFAIK the only solution to do what you want to achieve while avoiding duplicate subscriptions to the Observable .这并不漂亮,但 AFAIK 是唯一的解决方案,可以在避免重复订阅Observable同时完成您想要实现的目标。

<ng-container *ngIf="items$ | async as items; else empty">
  <ng-container *ngIf="items?.length > 0; else empty">
     ...
  </ng-container>
</ng-container>
<ng-template #empty>no favorite here</ng-template>

With a slight modification to the observable you can achieve this.通过对 observable 稍加修改,您可以实现这一点。

For example:例如:

items$: Observable<number[] | undefined> = of([1, 2, 3, 4]).pipe(map((items) => {
    if(items?.length > 0) {
      return items;
    }
    return undefined;
  }));

Here you need to use the pipe and map function additionally.这里需要额外使用管道和映射功能。 Then in the template file:然后在模板文件中:

<ng-container *ngIf="(items$ | async); else empty; let items">
  <button mat-menu-item *ngFor="let item of items">
      {{item}}
  </button>
</ng-container>
<ng-template #empty>no favorite here</ng-template>

Using this way only one subscription is created also it fallbacks to empty template if the array is empty.使用这种方式只创建一个订阅,如果数组为空,它也会回退到空模板。 Hope this would help you.希望这会帮助你。 You can find the stackblitz link here .您可以在此处找到 stackblitz 链接。

Why container?为什么是容器? True.真的。 In this case, there is not much difference.在这种情况下,没有太大区别。 ( https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ ) https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

<ng-template *ngIf="(items$ | async).length > 0">
   <button mat-menu-item *ngFor="let item of items$ | async">
      {{ item }}
   </button>
</ng-template>

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

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