代码之家  ›  专栏  ›  技术社区  ›  Rafael

角度创建选择分组选项

  •  1
  • Rafael  · 技术社区  · 8 年前

    我现在正在做一个利用大量信息的项目 选择 . 有没有办法用自然角度(5/6?)功能? 我尝试了ng select组件,但没有很好地执行。

    我的:

    <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>
    

    这是我的类变量

    disbursementTypeOptions = [
        {
            "key": 1,
            "title": "Przelew na konto",
            "group": "first",
        },
        {
            "key": 2,
            "title": "Czek Giro",
            "group": "second",
        },
    ];
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Pankaj Parkar    8 年前

    可以对组件中的分组对象进行切片、骰子和数组,然后使用 optgroup 具有 option 在选择中标记

    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>
    

    代码

    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)
        }))
    }
    
        2
  •  1
  •   Andrei Tătar    8 年前

    如果您不想添加lodash来使用 groupBy ,您可以使用 rxjs (因为它已经有角度)如下。如果您有静态数据(为什么不首先对其进行分组),那么这并不是很有用,但是对于异步数据可能很有用。

    const disbursementTypeOptions: Item[] = [
      {
        'key': 1,
        'title': 'Przelew na konto',
        'group': 'first',
      },
      {
        'key': 2,
        'title': 'Czek Giro',
        'group': 'second',
      },
    ];
    
    let groups: { group: string, items: Item[] }[];
    
    from(disbursementTypeOptions)
      .pipe(
        groupBy(v => v.group),
        mergeMap(group => group.pipe(toArray(), map(items => ({ group: group.key, items })))),
        toArray()
      )
      .subscribe(grouped => groups = grouped);
    
    推荐文章