首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >select / ngFor中的ngFor分组输出

select / ngFor中的ngFor分组输出
EN

Stack Overflow用户
提问于 2018-02-11 20:35:17
回答 1查看 1.3K关注 0票数 4

我有一个像这样的数据集

代码语言:javascript
复制
[{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选项组对它们进行分组。

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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中做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-11 21:29:49

下面是一个有用的例子:

构成部分:

代码语言:javascript
复制
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
  }
}

模板:

代码语言:javascript
复制
<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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48736166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档