【问题标题】:Angular ngFor split by divsAngular ngFor 按 div 分割
【发布时间】:2019-11-02 05:19:23
【问题描述】:

我有一个这样的数组

[a, b, c, d, e, f, g, h, i]

我的目标是用 ngFor 循环遍历它,将其拆分为 3 元素,输出应该是这样的

  <div class="wrapper">
     <div class="main">abc</div>
     <div class="main">def</div>
     <div class="main">ghi</div>
  </div>

所以我可以做的解决方案是

<div class="wrapper">
      <div *ngFor="let index = index; let letter of ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']">
        <div class="main" *ngIf="(index + 1) % 3 == 0">
            {{ letter }}
        </div>
    </div>
</div>

如您所见,我使用 ma​​in 类在 div 上创建了 div。但我不需要 ma​​in 类 div 上的任何 div。我需要它在示例中的显示方式。

【问题讨论】:

  • 创建一个临时数组或将三个字母组合在一起的管道。
  • 你为什么不在 ts 文件中创建新数组而只在 html 中遍历?
  • 是的,或者 lodash 块方法 + ng-container 删除 div
  • 如果你想使用一些角度指令而不实际渲染任何东西,你可以使用&lt;ng-container *ngFor="..."&gt;&lt;/ng-container&gt;
  • 你的逻辑不正确,ng-container 会移除 div 但不会得到 3 个一组的字母。

标签: javascript angular


【解决方案1】:

我不会将逻辑放入 HTML 代码中,而是在 Array 的 splicejoin 函数的帮助下使用主数组构造一个新数组。

所以整体代码是:

HTML:

<div class="wrapper">
    <ng-container *ngFor="let index = index; let letter of newArray">
        <div class="main">
            {{ letter }}
        </div>
    </ng-container>
</div>

TS 代码:

import { Component } from '@angular/core';

@Component({
  selector: 'form-field-overview-example',
  templateUrl: 'form-field-overview-example.html',
  styleUrls: ['form-field-overview-example.css'],
})
export class FormFieldOverviewExample {

  mainArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

  newArray : any[] = [];

  constructor() {
    this.divideAndJoinArray(3);
  }

  divideAndJoinArray(spliceAt : number){
    while (this.mainArray.length) {
      var str = (this.mainArray.splice(0, spliceAt).join(''));
      console.log(str)
      this.newArray.push(str);
    }
  }
}

Stackblitz Demo

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2018-10-27
    • 2018-01-17
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2019-09-08
    • 2019-03-03
    相关资源
    最近更新 更多