如何在 div 中对一组 divs/web 元素进行分组?

How to use Group a set of divs/web elements inside a div?

我正在尝试设置 Group/Ungroup 功能,例如 Word/Excel(用于选择图像)。但是问题出现在 对 ngForList 中的元素进行分组期间。下图(新设计)显示了选择 Cards/divs

后所需的输出

这里我尝试过的是尝试用下面的 Stackblitz link 复制:https://stackblitz.com/edit/group?file=app%2Fapp.component.html

在那个例子中,我们需要的是:

  1. 按 Id/ 或任何其他列排序(在分组期间失败)

  2. 将卡片分组(有效)

我需要的是等于undefined as ordered cards的地面。见图 2 或者

用于选择 div 的任何逻辑,将这些选定的 div 分组到列表中。

请帮我提供建议、文档和进一步的示例演示。

您有 3 个组:A 组、B 组和 undefined。第三组 undefined 存在,因为在 app.component.ts 中的 array 您没有为项目 36 设置任何 group

使用以下 array(在 app.component.ts 中)它应该可以工作:

array = [
    {
      "id": 1,
      "name": "item 1",
      "group": "Group A"
    },
    {
      "id": 2,
      "name": "item 2",
      "group": "Group A"
    },
    {
      "id": 3,
      "name": "item 3",
      "group": "Group A" // <-- this changed
    },
    {
      "id": 4,
      "name": "item 4",
      "group": "Group B"
    },
    {
      "id": 5,
      "name": "item 5",
      "group": "Group B"
    },
    {
      "id": 6,
      "name": "item 6",
      "group": "Group B" // <-- this changed
    }
  ];

我取消注释并编辑了第 3 项和第 6 项的 group

编辑/附录

如果您希望您的项目仍然按顺序 (1-6) 但仍将它们分组,您可以执行以下操作(另请参阅 updated stackblitz):

ngOnInit(){
    this.result = [];
    var currentGroup = ''; // <-- updated this line
    this.array.forEach(item => {
      if (item.group != currentGroup) {
        currentGroup = item.group;
        this.result.push({
          name: item.group,
          values: [],
        });
      }
      this.result[this.result.length - 1].values.push(item);
    });
  }