在select / ngFor中的angular5分组输出

时间:2018-02-11 20:35:17

标签: angular

我的数据集看起来像这样

[{id: "1", type: "Animal", name: "German Sheperd", family: "Canine" },
{id: "2", type: "Animal", name: "Poodle", family: "Canine" },
{id: "3", type: "Animal", name: "Pug", family: "Canine" },
{id: "4", type: "Animal", name: "Callico", family: "Feline" },
{id: "5", type: "Animal", name: "Siamese", family: "Feline" }]

我想使用HTML选项组对它们进行分组。

<select>
    <optgroup label="Canine">
        <option value="1">German Sheperd</option>
        <option value="2">Poodle</option>
        <option value="3">Pug</option>
    </optgroup>
    <optgroup label="Feline">
        <option value="4">Callico</option>
        <option value="5">Siamese</option>
    </optgroup>
</select>

我知道这不对 - 但这样的事情呢?

<select class="form-control input-sm "  [class.state-error]="showError('talent')" name="talent" formControlName="talent" >
                <optgroup *ngFor="let family of animals" label= {{family.family}} >

                    <option *ngFor="let thing of things" value= {{thing.id}}>
                        {{thing.name}}
                    </option>

                </optgroup>
            </select>

我如何在Angular5中执行此操作?

1 个答案:

答案 0 :(得分:1)

这是一个有效的例子:

组件:

export class AppComponent  {
  families: string[]; // it's cleaner to prepare your data in the model and then pass it to the template
  animals = [{id: "1", type: "Animal", name: "German Sheperd", family: "Canine" },
{id: "2", type: "Animal", name: "Poodle", family: "Canine" },
{id: "3", type: "Animal", name: "Pug", family: "Canine" },
{id: "4", type: "Animal", name: "Callico", family: "Feline" },
{id: "5", type: "Animal", name: "Siamese", family: "Feline" }];

  ngOnInit() {
    this.families = Array.from(new Set(this.animals.map(({family}) => family))); // get unique families
  }
}

模板:

<select class="form-control input-sm">
  <optgroup *ngFor="let family of families" 
            label= {{family}} >
      <ng-container *ngFor="let thing of animals" >
        <option *ngIf="thing.family === family" value={{thing.id}}>
            {{thing.name}}
        </option>
      </ng-container> 
  </optgroup>
</select>

你可以在这里玩它: https://stackblitz.com/edit/angular-d3ssum