【问题标题】:Angular 2: *ngFor in *ngForAngular 2:*ngFor 中的 *ngFor
【发布时间】:2017-09-20 15:52:30
【问题描述】:

以下场景在 javascript 中非常简单,但在 Angular 中运行时遇到了一些问题。

我有一个像这样的数组:

array a = ( "id" = 0, name = random(), column = 1, 2 or 3, blockrow= 1, 2 or 3)

使用 ngFor,我现在尝试创建一个网格,其中所有元素在此列中的列和块中分开。所以我当前的代码(有效但令人讨厌)。

<div *ngFor="let a of a">
  <template [ngIf]="a.column=='1'">
    <div *ngFor="let b of a">
      <template [ngIf]="b.blockrow=='1'">
        Block 1 in column 1{{b.name}}
      </template>
    </div>
    <div *ngFor="let b of a">
      <template [ngIf]="b.blockrow=='2'">
        Block 2 in column 1{{b.name}}
      </template>
    </div>
    <div *ngFor="let b of a">
      <template [ngIf]="b.blockrow=='3'">
        Block 3 in column 1{{b.name}}
      </template>
    </div>
  </template>
</div>

我为每一列运行类似的东西。这意味着我在同一个数组中循环了 12 次。有没有办法让它更漂亮?

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    您使用的语法错误应该是*ngIf 而不是[ngIf]

    <div *ngFor="let a of a">
      <template *ngIf="a.column=='1'">
        <div *ngFor="let b of a">
          <template *ngIf="b.blockrow=='1'">
            Block 1 in column 1{{b.name}}
          </template>
        </div>
        <div *ngFor="let b of a">
          <template *ngIf="b.blockrow=='2'">
            Block 2 in column 1{{b.name}}
          </template>
        </div>
        <div *ngFor="let b of a">
          <template *ngIf="b.blockrow=='3'">
            Block 3 in column 1{{b.name}}
          </template>
        </div>
      </template>
    </div>
    

    【讨论】:

    • 改了顶部,编辑器使用角度1,但这不是我的问题。只是想知道是否有办法不那么频繁地运行循环。
    • 我没找到你
    • 在我的示例中,我在同一个数组中循环 4 次。为了让它完全工作,我需要这个 3 次,这意味着 12 次循环通过同一个数组。在我看来,这是非常低效的。在普通的 JS 中,我可以做同样的事情,只通过数组一次。所以我的问题是,有没有办法更好地完成这段代码?类似于 if b.blockrow == 1 -> 添加到 div1,如果 b.blockrow == 2 添加到 div 2。
    • 顺便说一句。尝试使用 *ngIf 在我的 Angular 应用程序中进行更改,但它不起作用。文档还说 [ngIf] for template。
    • 究竟是什么问题。
    【解决方案2】:

    在您的组件中,使用 JavaScript 构建一个数组数组,其中 a 的元素位于正确的坐标处,然后在 *ngFor 中使用 *ngFor:

    <div *ngFor="let row of rows">
      <div *ngFor="let col of row">
        Block {{col.blockrow}} in column {{col.column}} {{col.name}}
      </div>
    </div>
    

    如果多个块具有相同的坐标,则可能需要第三个 *ngFor。

    【讨论】:

    • 所以我可以通过这种方式处理多维数组。完美,谢谢,这正是我想要的。
    猜你喜欢
    • 2018-10-13
    • 2018-06-01
    • 2018-04-25
    • 2017-05-07
    • 2016-09-17
    • 2017-05-24
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多