Angular creating a SELECT grouping the options

Raf*_*ael 1 angular

I'm working on a project right now that makes use of plenty of information on selects. Is there any way to group this information using native Angular (5/6?) functions? I tried the ng-select component but did not perform well.

My :

<div class="form-group">
  <label for="disbursementType" class="ng-required">Typ wyp?aty</label>
  <select id="disbursementType" class="form-control"
          name="disbursementType" required [(ngModel)]="hero.power" #power="ngModel" >
    <option *ngFor="let disbursementTypeOption of disbursementTypeOptions" 
            [value]="disbursementTypeOption.key">{{disbursementTypeOption.title}}</option>
  </select>
</div>
Run Code Online (Sandbox Code Playgroud)

And this is my class variable

disbursementTypeOptions = [
    {
        "key": 1,
        "title": "Przelew na konto",
        "group": "first",
    },
    {
        "key": 2,
        "title": "Czek Giro",
        "group": "second",
    },
];
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 5

您可以将组件内的对象切片、切块和数组分组,然后在 select 内使用optgroupwithoption标签

HTML

<select id="disbursementType" class="form-control"
      name="disbursementType" required [(ngModel)]="hero.power" #power="ngModel" >
  <optgroup [attr.label]="group.name" *ngFor="let group of groupedArray">
    <option *ngFor="let disbursementTypeOption of group.values" 
        [value]="disbursementTypeOption.key">
      {{disbursementTypeOption.title}}
    </option>
  </optgroup>
</select>
Run Code Online (Sandbox Code Playgroud)

代码

unique: string[];
groupedArray: any[]
formatArray() {
    this.unique = [...new Set(this.disbursementTypeOptions.map(item => item.group))];
    this.groupedArray = unique.map(i => ({
      name: i,
      values: disbursementTypeOptions.filter(d => d.group === i)
    }))
}
Run Code Online (Sandbox Code Playgroud)