簡體   English   中英

使用 ngFor 和 ngIf 在數組中迭代兩種不同的方式 - Angular

[英]Iterate two different ways in an array with ngFor and ngIf - Angular

我正在嘗試獲取此數組(最終將來自 API 以生成實際組件):

salesArray = [0, 1, 2, 3, 4, 5, 6, 7];

允許我在 Bootstrap 行和列中多次生成組件。

這個想法是提供兩種不同的視圖,用戶可以通過一個按鈕來切換。 這部分與問題沒有直接聯系。

第一個視圖 = 一個帶有 3 col-4 的 Bootstrap 行,所以結果應該是:

0 - 1 - 2

3 - 4 - 5

6 - 7 - 空列

第二個視圖 = 帶有 2 col-4 的 Bootstrap 行(不是 col-6,因為將從 API 進一步調用的元素必須保持相同的大小),所以結果應該是:

0 - 1

2 - 3

4 - 5

6 - 7

這是我現在的代碼:

<div class="container-fluid">
  <div class="row">
  <div class="col-9">
        <ng-container *ngIf="screenResolution == 'Desktop'">
            <ng-container *ngFor="let item of salesArray; let i = index;">
                <div class="row" *ngIf="i%3 === 0">
                    <ng-container *ngFor="let item of salesArray; let i = index;">
                    <div class="col-4">
                        {{ i }}
                        <!-- <srp-sale-block [dataView]=dataToDisplay></srp-sale-block> -->
                    </div>
                </ng-container>
                </div>
            </ng-container>
        </ng-container>
  </div>
  </div>
</div>

現在,我設法每三個組件生成一行,但在此之后循環再次遍歷所有數組,我不知道如何按行僅顯示 2 或 3 個數字,然后繼續下一個系列. 所以第一行是 0 - 1 - 2,第二行是 3 - 4 - 5 ...

謝謝。

您可能可以僅使用[ngClass]指令根據分辨率應用引導列類。 如果分辨率是桌面,則應用類col-4為您提供 3 列,否則應用類col-6為您提供 2 列。

銷售.component.html

<div class="row">
  <ng-container *ngFor="let item of salesArray">
    <div [ngClass]="
        { 'col-4' : resolution === 'Desktop', 'col-6' : resolution === 'Mobile' }">
      {{item}}
    </div>
  </ng-container>
</div>

不太確定這是否是您要查找的內容。 這是一個stackblitz示例......

https://stackblitz.com/edit/angular-bootstrap-4-starter-jsiaw1?file=src/app/sales/sales.component.html

暫無
暫無

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

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