Angular Material Select : Groups of Options

By Arvind Rai, October 09, 2019
Angular Material provides <mat-optgroup> element to group common options under a subheading in <mat-select> element. The name for a group is set using label property of <mat-optgroup>. We can disable entire <mat-optgroup> using its disabled property in the same way as we do for <mat-option> element. To create groups of options for native <select matNativeControl>, we need to use <optgroup> element. Now let us discuss creating Angular Material Select Option group in detail.

Technologies Used

Find the technologies being used in our example.
1. Angular 8.2.8
2. Angular Material 8.2.1
3. Node.js 12.5.0
4. NPM 6.9.0

Groups of Options using <mat-optgroup> in <mat-select>

To create groups of options in <mat-select> element, we need to use <mat-optgroup> element and provide subheading using its label property.
1. Create Groups of Options
<mat-form-field>
  <mat-label>Select book</mat-label>  
  <mat-select>
    <mat-option>-- None --</mat-option>
    <mat-optgroup label="Epic">
      <mat-option value="Ramayana">Ramayana</mat-option>
      <mat-option value="Mahabharata">Mahabharata</mat-option>
    </mat-optgroup>
    <mat-optgroup label="Science">
      <mat-option value="Physics">Physics</mat-option>
      <mat-option value="Chemistry">Chemistry</mat-option>
    </mat-optgroup>
    <mat-optgroup label="Novel">
      <mat-option value="Godan">Godan</mat-option>
      <mat-option value="Karmbhumi">Karmbhumi</mat-option>
    </mat-optgroup>  
  </mat-select>
</mat-form-field> 
Find the print screen.
Angular Material Select : Groups of Options
2. Disable Groups of Options
To disable groups of options, use disabled property with <mat-optgroup> element.
<mat-form-field>
  <mat-label>Select book</mat-label>  
  <mat-select>
    <mat-option>-- None --</mat-option>
    <mat-optgroup label="Epic" disabled>
     ------
    </mat-optgroup>
    <mat-optgroup label="Science">
      ------
      <mat-option value="Chemistry" disabled>Chemistry</mat-option>
    </mat-optgroup>
    <mat-optgroup label="Novel">
     ------
    </mat-optgroup>  
  </mat-select>
</mat-form-field> 
3. Groups of Options with Multiple Selection
To enable multiple selection, use multiple attribute with <mat-select> element.
<mat-form-field>
  <mat-label>Select books</mat-label>  
  <mat-select multiple >
    ------
  </mat-select>
</mat-form-field> 

Groups of Options using <optgroup> in <select matNativeControl>

To create groups of options in <select matNativeControl> element, we need to use <optgroup> element and provide subheading using its label property.
1. Create Groups of Options
<mat-form-field>
  <mat-label>Select profile</mat-label>  
  <select matNativeControl>
    <optgroup label="Epic">
      <option value="Ramayana">Ramayana</option>
      <option value="Mahabharata">Mahabharata</option>
    </optgroup>
    <optgroup label="Science">
      <option value="Physics">Physics</option>
      <option value="Chemistry">Chemistry</option>
    </optgroup>
    <optgroup label="Novel">
      <option value="Godan">Godan</option>
      <option value="Karmbhumi">Karmbhumi</option>
    </optgroup> 
  </select>
</mat-form-field> 
2. Disable Groups of Options
To disable groups of options, use disabled property with <optgroup> element.
<mat-form-field>
  <mat-label>Select book</mat-label>  
  <select matNativeControl >
    <optgroup label="Epic" disabled>
     ------
    </optgroup>
    <optgroup label="Science">
      ------
      <option value="Chemistry" disabled>Chemistry</option>
    </optgroup>
    <optgroup label="Novel">
     ------
    </optgroup>  
  </select>
</mat-form-field> 
Groups of Options with Multiple Selection
To enable multiple selection, use multiple attribute with <select matNativeControl> element.
<mat-form-field>
  <mat-label>Select books</mat-label>  
  <select matNativeControl multiple>
    ------
  </select>
</mat-form-field> 

Complete Example

book.service.ts
import { Injectable } from '@angular/core';

const ALL_BOOKS = [
  {
    groupName: "Epic",
    books: [
      { id: 'Ramayana', viewName: 'Ramayana' },
      { id: 'Mahabharata', viewName: 'Mahabharata' }
    ]
  },
  {
    groupName: "Science",
    books: [
      { id: 'Physics', viewName: 'Physics' },
      { id: 'Chemistry', viewName: 'Chemistry' }
    ]
  },
  {
    groupName: "Novel",
    books: [
      { id: 'Godan', viewName: 'Godan' },
      { id: 'Karmbhumi', viewName: 'Karmbhumi' }
    ]
  }
]

@Injectable({
  providedIn: 'root'
})
export class BookService {
  getAllBooks() {
    return ALL_BOOKS;
  }
  saveBooks(books) {
    console.log(JSON.stringify(books));
  }
} 
select-option.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, Validators } from '@angular/forms';
import { BookService } from './book.service';

@Component({
  selector: 'app-select',
  templateUrl: './select-option.component.html'
})
export class SelectOptionComponent implements OnInit {
  allBooks: any;

  constructor(private formBuilder: FormBuilder, private bookService: BookService) { }

  ngOnInit() {
    this.allBooks = this.bookService.getAllBooks();
  }
  bookForm = this.formBuilder.group({
    book: ['', Validators.required],
    refBooks: [null, Validators.required]
  });

  get book() {
    return this.bookForm.get('book');
  }
  get refBooks() {
    return this.bookForm.get('refBooks');
  }
  onFormSubmit() {
    this.bookService.saveBooks(this.bookForm.value);
    this.resetForm();
  }
  resetForm() {
    this.bookForm.reset();
  }
} 
select-option.component.html
<h3>Angular Material Select Demo</h3>
<form [formGroup]="bookForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>
    <mat-label>Select favorite book</mat-label>
    <mat-select formControlName="book" [value]="book1">
      <mat-option>-- None --</mat-option>
      <mat-optgroup *ngFor="let groupBooks of allBooks" [label]="groupBooks.groupName">
        <mat-option *ngFor="let book of groupBooks.books" [value]="book.id">{{book.viewName}}</mat-option>
      </mat-optgroup>
    </mat-select>
    <mat-error *ngIf="book.hasError('required')">
      Favorite book required.
    </mat-error>
  </mat-form-field>
  <br/>
  <br/>
  <mat-form-field>
    <mat-label>Select reference books</mat-label>
    <mat-select formControlName="refBooks" multiple>
      <mat-optgroup *ngFor="let groupBooks of allBooks" [label]="groupBooks.groupName">
        <mat-option *ngFor="let book of groupBooks.books" [value]="book.id">{{book.viewName}}</mat-option>
      </mat-optgroup>
    </mat-select>
    <mat-error *ngIf="refBooks.hasError('required')">
      Reference books required.
    </mat-error>
  </mat-form-field>
  <br/>
  <br/>
  <button mat-raised-button>Submit</button>
  <button mat-raised-button type="button" (click)="resetForm()">Reset</button>
</form> 
Find the HTML template using <select matNativeControl> element.
select-option-native.component.html
<h3>Angular Material Select Demo with Native Select</h3>
<form [formGroup]="bookForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>
    <mat-label>Select favorite book</mat-label>
    <select matNativeControl formControlName="book" [value]="book1">
      <optgroup *ngFor="let groupBooks of allBooks" [label]="groupBooks.groupName">
        <option *ngFor="let book of groupBooks.books" [value]="book.id">{{book.viewName}}</option>
      </optgroup>
    </select>
    <mat-error *ngIf="book.hasError('required')">
      Favorite book required.
    </mat-error>
  </mat-form-field>
  <br/>
  <br/>
  <mat-form-field>
    <mat-label>Select reference books</mat-label>
    <br/>
    <br/>
    <select matNativeControl formControlName="refBooks" multiple>
      <optgroup *ngFor="let groupBooks of allBooks" [label]="groupBooks.groupName">
        <option *ngFor="let book of groupBooks.books" [value]="book.id">{{book.viewName}}</option>
      </optgroup>
    </select>
    <mat-error *ngIf="refBooks.hasError('required')">
      Reference books required.
    </mat-error>
  </mat-form-field>
  <br/>
  <br/>
  <button mat-raised-button>Submit</button>
  <button mat-raised-button type="button" (click)="resetForm()">Reset</button>
</form> 
app.component.ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `
      <app-select></app-select>
      <app-select-native></app-select-native>
  `
})
export class AppComponent {
} 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule }    from '@angular/forms'; 
import { MatSelectModule, MatInputModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppComponent } from './app.component';
import { SelectOptionComponent } from './select-option.component';
import { SelectOptionNativeComponent } from './select-option-native.component';

@NgModule({
  declarations: [
    AppComponent,
    SelectOptionComponent,
    SelectOptionNativeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MatSelectModule,
    MatInputModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Select : Groups of Options

Reference

Angular Material Select

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us