How to Use Angular Material Form Controls Select Component with Example

How to Use Angular Material Form Controls Select Component with Example

In this Angular Material tutorial, we will show you how to use Angular Material Form Controls select component with the working examples. An angular Material Form control is an essential component, especially when working with the data. Angular Material components tutorial about Form controls select <mat-select> complete with the working examples

The series of a comprehensive step by step Angular Material components tutorial about Form controls select complete with the working examples

In this Angular Material series, we will show you how to use Angular Material Form Controls select component with the working examples. An angular Material Form control is an essential component, especially when working with the data. There are some Angular Material Form Controls like autocomplete, checkbox, date picker, form field, input, radio button, select, slider, and slide toggle. This time we will show you examples of Angular Material Form Controls Select .

Table of Contents:

  • Preparation
  • Basic Select Example
  • Select in Reactive Form Example
  • Grouping Option Example
  • Multiple Select Example
  • Nested Select Example
  • Custom Style Example

The following tools, frameworks, and libraries or modules are required for this tutorial.

  1. Node.js
  2. Angular 8
  3. Angular Material
  4. Terminal (Linux/Mac) or Node Command Line (Windows)
  5. Text Editor or IDE (We use VSCode)
Preparation

We will bundle all of this Angular Material Form Controls Select examples in one application. For that, we will prepare all required Angular 8 applications and Angular Material 8. Now, we are creating an Angular 8 app using Angular CLI which needs Node.js and NPM to install or update it. Make sure you have to install Node.js and NPM before installing or updating Angular CLI. To install or update an Angular CLI type this command.

sudo npm install -g @angular/cli

Next, create a new Angular 8 app using Angular CLI by type this command.

ng new material-select

That command will create a new Angular 8 app with the name material-select and pass all questions as 'Y' then the Angular CLI will automatically install the required NPM modules. After finished, go to the newly created Angular 8 folder then run the Angular 8 app for the first time.

cd ./material-select
ng serve --open

Using that "--open" parameters will automatically open the Angular 8 in your default web browser. Here's the Angular 8 default page look like.

Next, type this command to install Angular Material using Angular CLI's install schematics.

ng add @angular/material

Leave all questions as default to finish the installation.

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink        [ Preview: https://mate
rial.angular.io?theme=indigo-pink ]
? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes

Next, open the Angular application project with your text editor or IDE. Open and edit src/app/app.module.ts then add these required imports of @angular/forms FormsModule, ReactiveFormsModule, @angular/material MatSelectModule, and MatFormFieldModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';

Register the above modules to @NgModule imports.

imports: [
  BrowserModule,
  AppRoutingModule,
  BrowserAnimationsModule,
  FormsModule,
  ReactiveFormsModule,
  MatSelectModule,
  MatFormFieldModule
],

Now, the Angular Material Form Controls Components and Angular Reactive Form modules are ready to use in Angular Components.

Basic Select Example

For basic Angular Material Form Controls Select example, we need to create an Angular component first. Type this command in the Terminal or VSCode terminal to create a new Angular component.

ng g component basic

Next, open and edit "src/app/app-routing.module.ts" then add this import.

import { BasicComponent } from './basic/basic.component';

Add that BasicComponent to the routes constant.

const routes: Routes = [
  {
    path: 'basic',
    component: BasicComponent,
    data: { title: 'Basic Select Example' }
  },
];

Next, open and edit "src/app/app.component.html" then replace all HTML/Angular template with these.

<div class="container">
  <ul>
    <li><a [routerLink]="['/basic']">Basic Select Example</a></li>
  </ul>

  <router-outlet></router-outlet>
</div>

Give it a little style, by open and edit "src/app/app.component.scss" then add these lines of SCSS codes.

.container {
  width: 500px;
  margin: 20px;
  padding: 20px;
}

Next, open and edit "src/app/basic/basic.component.html" then add this lines of example that wrapped by .

<h2>Basic mat-select Example</h2>
<mat-form-field>
  <mat-label>Your Team</mat-label>
  <mat-select>
    <mat-option *ngFor="let team of teams" [value]="team.name">
      {{team.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

This basic mat-select option (mat-option) loops by "teams" array. So, we need to add an array to the Typescript file. Open and edit "src/app/basic/basic.component.ts" then add this array variable before the constructor.

teams: any[] = [
    { name: 'Liverpool' },
    { name: 'Manchester City' },
    { name: 'Manchester United' },
    { name: 'Arsenal' },
    { name: 'Leicester City' },
    { name: 'Chelsea' },
    { name: 'Tottenham Hotspur' },
];

Now, the basic with will be like this.

The next example is to get the selected value to console or display it to the text. Still, on basic.component.ts, add this variable before the list variable.

selectedItem: string;

Next, add ([ngModel]) to "src/app/basic/basic.component.html" that point to previously created variable. Also, add a

to display the result of the selected option.

<h2>Basic mat-select Example</h2>
<mat-form-field>
  <mat-label>Your Team</mat-label>
  <mat-select [(ngModel)]="selectedItem">
    <mat-option *ngFor="let team of teams" [value]="team.name">
      {{team.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

<h3>Your Team is: {{selectedItem}}</h3>

Select in Reactive Form Example

This example is the most use in almost every Angular application that uses Form to input some data. Including show error message on every invalid selection using ErrorStateMatcher components. First, we will create an Angular Reactive Form to add new data. Generate a new Angular component for this example.

ng g component reactive

Add that generated component to the "src/app/app-routing.module.ts" and add a link to "src/app/app.component.html" as the previous example. Also, add that and additional Angular Material component (MatIconModule, MatCardModule) to the "src/app/app.module.ts" as the previous Angular Material configuration. Open and edit "src/app/reactive/reactive.component.ts" then add this import.

import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

Add MyErrorStateMatcher class that implements ErrorStateMatcher before the ReactiveComponent class.

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

Add these variables before the constructor.

  questionerForm: FormGroup;
  position = '';
  industry = '';
  experience = 0;
  matcher = new MyErrorStateMatcher();
  positions: any[] = ['Programmer', 'Businness Analyst', 'Designer', 'DBA'];
  industries: any[] = ['Software', 'Marketplace', 'Education', 'Mining'];
  experiences: any[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Initialize FormGroup and FormControls using FormBuilder inside the NgOnInit function.

  ngOnInit() {
    this.questionerForm = this.formBuilder.group({
      position: ['', Validators.required],
      industry: ['', Validators.required],
      experience: [null, Validators.required]
    });
  }

Add a form submit function to check the selected items to the console.

  onFormSubmit() {
    if (this.questionerForm.valid) {
      console.log(this.questionerForm.value);
    } else {
      return;
    }
  }

Next, implement the HTML or Angular template by open and edit "src/app/reactive/reactive.component.html" then replace all tags with these.

<mat-card>
  <form class="example-form" [formGroup]="questionerForm" (ngSubmit)="onFormSubmit()">
    <mat-form-field class="example-full-width">
      <mat-label>Position</mat-label>
      <mat-select formControlName="position" [errorStateMatcher]="matcher">
        <mat-option *ngFor="let pos of positions" [value]="pos">
          {{pos}}
        </mat-option>
      </mat-select>
      <mat-error *ngIf="questionerForm.get('position').hasError('required')">
        You must make a selection
      </mat-error>
    </mat-form-field>
    <mat-form-field class="example-full-width">
        <mat-label>Your Position</mat-label>
      <mat-select formControlName="industry" [errorStateMatcher]="matcher">
        <mat-option *ngFor="let ind of industries" [value]="ind">
          {{ind}}
        </mat-option>
      </mat-select>
      <mat-error *ngIf="questionerForm.get('industry').hasError('required')">
          You must make a selection
      </mat-error>
    </mat-form-field>
    <mat-form-field class="example-full-width">
      <mat-label>Experience</mat-label>
      <mat-select formControlName="experience" [errorStateMatcher]="matcher">
        <mat-option *ngFor="let exp of experiences" [value]="exp">
          {{exp}}
        </mat-option>
      </mat-select>
      <mat-error *ngIf="questionerForm.get('experience').hasError('required')">
          You must make a selection
      </mat-error>
    </mat-form-field>
    <div class="button-row">
      <button type="submit" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
    </div>
  </form>
</mat-card>

To set the initial value as the Edit form. Add this function.

  setValues() {
    this.questionerForm.setValue({
      position: 'Designer',
      industry: 'Mining',
      experience: 6
    });
  }

Then call that function in NgOnInit function.

  ngOnInit() {
    ...
    this.setValues();
  }

So, this example will look like this.

Grouping Option Example

For this example, first, we have to create a new component. Do exactly like the previous example with the component name "grouping". So, this mat-select contain mat-optgroup which the group name disabled (can't choose) and each mat-optgroup has their own mat-option. Open and edit "src/app/grouping/grouping.component.ts" then add this nested array variable.

  groups: any[] = [
    {
      groupName: 'Group A',
      teams: [
        { teamName: 'Real Madrid' },
        { teamName: 'Bayern Muenchen' },
        { teamName: 'Juventus' },
        { teamName: 'Manchester City' },
      ]
    },
    {
      groupName: 'Group B',
      teams: [
        { teamName: 'Inter Milan' },
        { teamName: 'Ajax Amsterdam' },
        { teamName: 'Barcelona' },
        { teamName: 'Tottenham Hotspur' },
      ]
    },
    {
      groupName: 'Group C',
      teams: [
        { teamName: 'Liverpool' },
        { teamName: 'AC Milan' },
        { teamName: 'PSG' },
        { teamName: 'Borussia Dortmun' },
      ]
    },
  ];

Next, open and edit "src/app/grouping/grouping.component.html" then replace all HTML tags or Angular template with these.

<mat-form-field>
  <mat-label>UEFA Champions Team</mat-label>
  <mat-select>
    <mat-optgroup *ngFor="let group of groups" [label]="group.groupName"
                  [disabled]="group.disabled">
      <mat-option *ngFor="let team of group.teams" [value]="team.teamName">
        {{team.teamName}}
      </mat-option>
    </mat-optgroup>
  </mat-select>
</mat-form-field>

So, this example will look like this.

Multiple Select Example

Using only mat-select is the single selection mode by default. To make it multiple selections, just add a "multiple" attribute to the . Before implementing this example, create a new Angular component with the name "multiple". Do as the previous component to register this new component to the routing and main component.

Next, open and edit "src/app/multiple/multiple.component.ts" then add this array os string variable.

skills: any[] = [ 'Java', 'Javascript', 'Angular', 'React', 'Vue', 'MySQL', 'MongoDB', 'Python' ];

Next, open and edit "src/app/multiple/multiple.component.html" then replace all HTML tags with these.

<mat-form-field>
  <mat-label>Choose Your Skills</mat-label>
  <mat-select multiple>
    <mat-option *ngFor="let skill of skills" [value]="skill">{{skill}}</mat-option>
  </mat-select>
</mat-form-field>

And this example will look like this.

Nested Select Example

Nested select in this example is two or more dan depending on the first . On first selection it send the value to the second options, and so on. Before implementing this example, create a new Angular component with the name "nested". Do as the previous component to register this new component to the routing and main component.

Next, open and edit "src/app/nested/nested.component.ts" then add this nested array of objects and empty array variables.

  groups: any[] = [
    {
      groupName: 'Group A',
      teams: [
        {
          teamName: 'Real Madrid',
          players: [
            { playerName: 'Karim Benzema' },
            { playerName: 'Luca Modric' },
            { playerName: 'Eden Hazard' },
          ]
        },
        {
          teamName: 'Bayern Munich',
          players: [
            { playerName: 'Phillipe Coutinho' },
            { playerName: 'Benjamin Pavard' },
            { playerName: 'Thomas Muller' },
          ]
        },
        {
          teamName: 'Juventus',
          players: [
            { playerName: 'Christiano Ronaldo' },
            { playerName: 'Aaron Ramsey' },
            { playerName: 'Emre Can' },
          ]
        },
        {
          teamName: 'Manchester City',
          players: [
            { playerName: 'David Silva' },
            { playerName: 'Leroy Sane' },
            { playerName: 'Riyad Mahrez' },
          ]
        },
      ]
    },
    {
      groupName: 'Group B',
      teams: [
        {
          teamName: 'Liverpool',
          players: [
            { playerName: 'Sadio Mane' },
            { playerName: 'Robertson' },
            { playerName: 'Fabinho' },
          ]
        },
        {
          teamName: 'AC Milan',
          players: [
            { playerName: 'Ibrahimovic' },
            { playerName: 'Andrea Conti' },
            { playerName: 'Fabio Borini' },
          ]
        },
        {
          teamName: 'PSG',
          players: [
            { playerName: 'Kylian Mbappe' },
            { playerName: 'Edison Cavani' },
            { playerName: 'Thiago Silva' },
          ]
        },
        {
          teamName: 'Borussia Dortmund',
          players: [
            { playerName: 'Axel Witsel' },
            { playerName: 'Mats Hummels' },
            { playerName: 'Marco Reus' },
          ]
        },
      ]
    },
  ];
  teams: any[] = [];
  players: any[] = [];

Next, open and edit "src/app/nested/nested.component.html" then replace all HTML tags with these.

<mat-form-field class="field-full-width">
  <mat-label>UEFA Group</mat-label>
  <mat-select (selectionChange)="showTeams($event)">
    <mat-option *ngFor="let group of groups" [value]="group">
      {{group.groupName}}
    </mat-option>
  </mat-select>
</mat-form-field>
<mat-form-field class="field-full-width">
  <mat-label>Group Team</mat-label>
  <mat-select (selectionChange)="showPlayers($event)">
    <mat-option *ngFor="let team of teams" [value]="team">
      {{team.teamName}}
    </mat-option>
  </mat-select>
</mat-form-field>
<mat-form-field class="field-full-width">
  <mat-label>Team Player</mat-label>
  <mat-select>
    <mat-option *ngFor="let player of players" [value]="player.playerName">
      {{player.playerName}}
    </mat-option>
  </mat-select>
</mat-form-field>

And this example will look like this.

Custom Style Example

As usual, we will put a custom style for mat-select in a new Angular component. For that, do as the previous example to add and register this new component. Give it name "custom" when generating a new component.

Next, open and edit "src/app/custom/custom.component.ts" then modify and add these imports.

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormControl } from '@angular/forms';

To make custom style applied to mat-select-panel, add this line to @Component.

@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

Open and edit "src/app/custom/custom.component.html" then replace all HTML tags with these.

<mat-form-field>
  <mat-label>Macbook Space Grey</mat-label>
  <mat-select panelClass="space-grey">
    <mat-option value="small">Macbook Pro 13"</mat-option>
    <mat-option value="mid">Macbook Pro 15"</mat-option>
    <mat-option value="large">Macbook Pro 16"</mat-option>
  </mat-select>
</mat-form-field>

Next, add a style class to "src/app/custom/custom.component.scss".

.space-grey.mat-select-panel {
  background: rgba(101,115,126, 0.5);
}

To customize the select box add this style.

.mat-select {
  width: 500px !important;
  border: solid 1px rgba(101,115,126, 0.5);
  padding: 10px;
}

And here this example looks like.

That it's, the example of Angular Material Form Controls Select . As usual, you can get full source codes in our GitHub.

If you don’t want to waste your time design your own front-end or your budget to spend by hiring a web designer then Angular Templates is the best place to go. So, speed up your front-end web development with premium Angular templates. Choose your template for your front-end project here.

Thanks!

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company