簡體   English   中英

如何在 Angular 中使用 ngFor 僅顯示某些數據類型?

[英]How do I display only certain data types with ngFor in Angular?

我正在遍歷名為“fruits”的數組,其中包含“FruitService”類型的對象 - 我定義並想要顯示每個元素的 class,但在刪除它們之后(我意識到這很奇怪 - 沒有 db)它們變成了“ undefined” 污染了我的數組。 我不希望這些顯示(它們顯示為空白)所以我只想顯示“FruitService”對象。 我怎么做?

<ul>

<li *ngFor="let fruit of fruits">
{{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}

</ul>

您可以使用 pipe 過濾它們,也可以檢查它們是否真實:

<ul>
  <ng-container *ngFor="let fruit of fruits">
    <li *ngIf="!!fruit">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }} 
    </li>
  <ng-container>
</ul>

使用 pipe 的解決方案:

<ul>
  <ng-container>
    <li *ngFor="let fruit of fruits | defined">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }} 
    </li>
  <ng-container>
</ul>
@Pipe({
  name: 'defined'
})
export class DefinedPipe implements PipeTransform {
  transform(array: any[]): any[] {
    return array.filter(element => !!element);
  }
}

這個問題在 controller 中得到了更好的處理。 理想情況下,刪除相應元素時,數組中不應有undefined的元素。 它們實際上應該從數組中刪除。

也就是說,您可以在模板中進行簡單的檢查,以查看元素是否在渲染之前定義

<ul>
  <ng-container *ngFor="let fruit of fruits">
    <li *ngIf="fruit">
      {{ fruit.name }}  price: {{ fruit._price }}   qty: {{ fruit.qty }}
    </li>
  </ng-container>
</ul>

ng-container標簽將在最終的 DOM 中被注釋掉,並且不會生成額外的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM