简体   繁体   English

角度5 * ngIf否则渲染div尽管nocontent

[英]Angular 5 *ngIf else rendering div despite nocontent

I'm using 我正在使用

Angular 5.2 Angular 5.2

Firestore 公司的FireStore

Using *ngIf isContent else noContent , I am trying to render an Observable only if it's populated with data. 使用*ngIf isContent else noContent ,我试图只在它填充了数据时才渲染Observable。 The logic isn't hitting the else statement. 逻辑没有达到else语句。 It's rendering isContent even when there's no data. 它的渲染isContent即使没有数据。 I have poured through these similar stack overflow questions and it looks like my syntax is correct. 我已经倾注了这些类似的堆栈溢出问题 ,看起来我的语法是正确的。 What am I doing wrong? 我究竟做错了什么?

Here's the code. 这是代码。

<ng-container *ngIf="months2025 | async as months; else nocontent">

  #### RENDERING REGARDLESS OF MONTHS2025 ####
  <div class="column">
    <h1>2025</h1> #### <-- THIS SHOWS UP ####
    <ul>
      <li *ngFor="let month of months">
        <a href={{month.url}}> {{ month.fileName }} </a>
      </li>
    </ul>
  </div>

</ng-container>

#### NOT RENDERING WHEN NOCONTENT ####
<ng-template #nocontent>
</ng-template>

Here is the component.ts 这是component.ts

export class MinutesComponent {
  monthsArray2025: AngularFirestoreCollection<any>;
  months2025: Observable<any[]>;

  constructor(private afs: AngularFirestore) {
    this.monthsArray2025 = afs.collection<any>('minutes', ref => ref.where('year', '==', 2025);
    this.months2025 = this.monthsArray2025.valueChanges();
  }
}

It looks like you are getting an empty array from your observable ie [] which is truthy . 看起来你从你的observable得到一个空数组,即[]这是真正的

You need to check for length as well. 您还需要检查长度。

<ng-container *ngIf="(months2025 | async) as months && months.length>0; else nocontent">

As I mentioned in my comment there is an open issue to allow a construct where such a check is possible in angular . 正如我在评论中提到的,有一个公开的问题,允许一个构造,其中这种检查可能是有角度的

One workaround is to use a map to force undefined/null when you have empty array. 一种解决方法是使用映射在空数组时强制undefined / null。

 this.months2025 = this.monthsArray2025.valueChanges().pipe(map(mnths=>mnths && mnths.length>0?mnths:undefined));

Another is to use two different *ngIf as mentioned by @John here 另一个是使用*ngIf 在这里提到的两个不同的*ngIf

So, there is a Github issue about this topic. 所以,关于这个主题有一个Github问题 For now, the simplest workaround I found is a pair of *ngIf containers. 目前,我找到的最简单的解决方法是一对* ngIf容器。

<ng-container *ngIf="months2025 | async as months">
  <ng-container *ngIf="months.length > 0; else nocontent">
    <div class="column">
      <li *ngFor="let month of months">
        <a href={{month.url}}> {{ month.fileName }} </a>
      </li>
    </div>
  </ng-container>
</ng-container>

<ng-template #nocontent>
</ng-template>

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

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