select/ngFor 中的 angular5 分组输出

标签 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 中做到这一点?

最佳答案

这是一个工作示例:

组件:

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

关于select/ngFor 中的 angular5 分组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736166/

相关文章:

Angular 为 ngFor 中的每个元素调用 ngAfterContentInit

angular - 未捕获( promise ): TypeError: component. canDeactivate 不是函数

angularfire2 在保存模型对象之前获取新的 pushid

javascript - 以 Angular 4 更改元素 <a> 的属性

javascript - 如何调试zone.js异常?

angular - 通过 Share_Target 将图像从 whatsapp 共享到 angular 应用程序不起作用

javascript - Angular 4 单元测试错误 - 无法在 'send' : Failed to load 'XMLHttpRequest' 上执行 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'

Angular 2 NgIf,不按条件渲染容器元素但显示其子元素

angular - 如何根据其他两个日期选择器字段在日期选择器字段上设置最小值和最大值 - Angular Material

json - 从 API 中解析 JSON 字符串