簡體   English   中英

角度5 * ngIf否則渲染div盡管nocontent

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

我正在使用

Angular 5.2

公司的FireStore

使用*ngIf isContent else noContent ,我試圖只在它填充了數據時才渲染Observable。 邏輯沒有達到else語句。 它的渲染isContent即使沒有數據。 我已經傾注了這些類似的堆棧溢出問題 ,看起來我的語法是正確的。 我究竟做錯了什么?

這是代碼。

<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>

這是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();
  }
}

看起來你從你的observable得到一個空數組,即[]這是真正的

您還需要檢查長度。

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

正如我在評論中提到的,有一個公開的問題,允許一個構造,其中這種檢查可能是有角度的

一種解決方法是使用映射在空數組時強制undefined / null。

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

另一個是使用*ngIf 在這里提到的兩個不同的*ngIf

所以,關於這個主題有一個Github問題 目前,我找到的最簡單的解決方法是一對* 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