j-p
j-p

Reputation: 3828

angular5 grouping output in a select / ngFor

I have a data set that look's like this

[{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" }]

I want to use the HTML option group to group them.

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

I know this isn't right - but something like this?

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

How would I do this in Angular5?

Upvotes: 4

Views: 1346

Answers (1)

Boris Lobanov
Boris Lobanov

Reputation: 2454

Here's a working example:

Component:

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

Template:

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

You can play with it here: https://stackblitz.com/edit/angular-d3ssum

Upvotes: 4

Related Questions