Angular 在一个下拉列表中同时显示主类别和子类别

Angular showing both main and sub category in one dropdown list

我有一个数组,需要它们出现在使用 Angular 的下拉列表中,其中主要部门和子部门都需要在同一个下拉列表中,并不是所有的主要部门都有子部门。以下是我想实现的输出下拉列表

departments=[
{id:"1",Category:"Human Resource", ChildOf: "0", Name: "Human Resource"},
{id:"2",Category:"IT", ChildOf: "0", Name: "IT"},
{id:"3",Category:"Account", ChildOf: "0", Name: "Account"},
{id:"4",Category:null, ChildOf: "2", Name: "Analysis"},
{id:"5",Category:null, ChildOf: "2", Name: "Repair"}
]

我不确定如何才能做到这一点。我需要使用 filter 函数还是可以使用 ngIfngFor 或两者的组合来完成?任何帮助都会很棒。非常感谢

如果可以的话,我会找到该数据的来源并对其进行重组,因为这是一种可怕的数据组织方式。像这样:

  departments = [
    { id: '1', category: 'Human Resource', children: [] },
    {
      id: '2',
      category: 'IT',
      children: [
        { id: '4', name: 'Analysis' },
        { id: '5', name: 'Repair' },
      ],
    },
    { id: '3', category: 'Account', children: [] },
  ];

那么html就是这样的:

<select>
  <ng-container *ngFor="let d of departments">
    <ng-container *ngIf="d.children.length === 0">
      <option>{{ d.category }}</option>
    </ng-container>
    <ng-container *ngIf="d.children.length > 0">
      <option *ngFor="let c of d.children">
        {{ d.category }} - {{ c.name }}
      </option>
    </ng-container>
  </ng-container>
</select>

如果您无法从源代码对其进行重组,那么您可以在将其提供给 html:

之前对其进行转换
  badData = [
    { id: '1', Category: 'Human Resource', ChildOf: '0', Name: 'Human Resource' },
    { id: '2', Category: 'IT', ChildOf: '0', Name: 'IT' },
    { id: '3', Category: 'Account', ChildOf: '0', Name: 'Account' },
    { id: '4', Category: null, ChildOf: '2', Name: 'Analysis' },
    { id: '5', Category: null, ChildOf: '2', Name: 'Repair' },
  ];

  departments: {
    id: string;
    category: string;
    children: { id: string; name: string }[];
  }[] = [];

  ngOnInit() {
    for (const d of this.badData) {
      if (d.Category && d.ChildOf === '0')
        this.departments.push({ id: d.id, category: d.Category, children: [] });
    }
    for (const d of this.badData) {
      if (d.ChildOf !== '0') {
        const parent = this.departments.find((el) => el.id === d.ChildOf);
        if (parent) parent.children.push({ id: d.id, name: d.Name });
      }
    }
  }