Angular 13 Select Dropdown with Reactive Forms Examples

Last updated on: by Digamber

In this Angular tutorial; I’m going to reveal how to profoundly work with Select Dropdown in Angular 13 application. We’ll learn how to create select dropdown component in angular using the Reactive Forms API.

Not just that, we will demystify the process on how to build single and multi select dropdown in angular, also how to integrate validation in angular select dropdown list component.

In this quick guide we will demonstrate how to quickly create, implement and validate select dropdown in Angular app.

Throughout Angular 13 select dropdown tutorial, you will see an example of Angular select box.

The primary Idea of this tutorial is to help you understand the entire concept of select dropdown in angular application. You will be bee seeing how to bind select dropdown component in Angular template easily.

You need to import and inject ReactiveFormsModule and FormsModule API to bring the select dropdown UI element in action using *ngFor loop.

Also, we will take help of SelectControlValueAccessor directive; It is extremely useful directive in angular, It is used to write select control values as well as listens to the select control changes.

This directive works with the following value accessors: FormControlDirective, FormControlName, and NgModel directives.

How to Create and Validate Multiple Select Dropdown in Angular

  • Step 1: Create Angular App
  • Step 2: Add Reactive Forms API
  • Step 3: Install Bootstrap Module
  • Step 4: Create Select Dropdown Component
  • Step 5: Add Style in Select Dropdown
  • Step 6: Test Select Dropdown in Angular

Install Latest Angular CLI

In the very first step, we will show you how to install latest version of Angular CLI. If Anyhow, you are using the older version then i would suggest to update the angular cli.

Here is the command that you have to execute.

npm install -g @angular/cli

Create Angular App

Now the angular CLI is installed, the important task, for now, is to generate the angular app.

You can invoke the given command to download the latest version of Angular.

ng new ng-demo

Move into the app’s root:

cd ng-demo

Add Reactive Forms API

In this step, we will be importing ReactiveFormsModule as well as FormsModule.

After importing the forms API, make sure to inject the apis into the imports array like given below code example.

Insert code in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Install Bootstrap Module

In this step, we will be adding an additional bootstrap module, this is for styling the angular select box. However, you may skip this step if don’t want any third party plugin support.

npm install bootstrap

To use the bootstrap make sure to add the css file path in the styles array within the angular.json file.

"styles": [
    "node_modules/bootstrap/dist/css/bootstrap.min.css",
    "src/styles.scss"
],

Create Select Dropdown Component

Go to app.component.html file, after getting into the file make sure to add the suggested code within the file.

<div class="container mt-5">
  <div class="row custom-wrapper">
    <h2 class="mb-3 text-center">Angular Select Dropdown Examle</h2>
    <form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
      <div class="d-grid">
        <select
          class="custom-select mb-3"
          (change)="changeCity($event)"
          formControlName="cityName"
        >
          <option value="">Choose City</option>
          <option *ngFor="let city of City" [ngValue]="city">
            {{ city }}
          </option>
        </select>
        <!-- error block -->
        <div class="invalid-feedback" *ngIf="isSubmitted && cityName?.invalid">
          <sup>*</sup>Please provide city name
        </div>
        <button type="submit" class="btn btn-danger btn-lg btn-block">
          Submit
        </button>
      </div>
    </form>
  </div>
</div>

Head over to app.component.ts file, after opening the file insert the following code into the file.

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  isSubmitted = false;
  City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan'];
  constructor(public fb: FormBuilder) {}
  registrationForm = this.fb.group({
    cityName: ['', [Validators.required]],
  });
  changeCity(e: any) {
    this.cityName?.setValue(e.target.value, {
      onlySelf: true,
    });
  }
  // Access formcontrols getter
  get cityName() {
    return this.registrationForm.get('cityName');
  }
  onSubmit(): void {
    console.log(this.registrationForm);
    this.isSubmitted = true;
    if (!this.registrationForm.valid) {
      false;
    } else {
      console.log(JSON.stringify(this.registrationForm.value));
    }
  }
}

Let us understand what we did in the above code example.

Created an array of city names that will be shown in the select dropdown options list.

Iterating city names data array to populate city names in the select dropdown list.

To add the value dynamically to select box via form control we are using (change)=”” event listener, it is listening to the changeCity() function. Why so? Because user may choose value based on his choice therefore we can not pre-filled the value. Instead we’ll use setValue() method to dynamically set the form control value.

The above code example’s context is concerned with Angular multiple select dropdown component. Angular offers SelectMultipleControlValueAccessor directive for selecting multiple options in select dropdown. This directive allows us to write multi-select control values in Angular forms and also listens to multi-select control changes.

To validate Angular select dropdown; we require to use Validators class with Reactive Forms. Therefore, we imported the Validators. module it will validate the required value of select options using getter method to access select options’s form control value.

Add Style in Select Dropdown

If you want to style the select box in angular you may use the following CSS code. If you want, you can also use your own custom css.

Open the styles.scss file and update the given code in the file.

@import url("https://fonts.googleapis.com/css?family=Muli:200,300,400,600");
body {
  font-family: "Muli", sans-serif;
  background: #7ddcd5;
}
h5 {
  font-weight: 600;
}
.custom-wrapper {
  max-width: 460px;
  margin: 0 auto 50px;
}
.h2,
h2 {
  font-size: 1.45rem;
}
label {
  font-size: 15px;
  font-weight: 600;
  color: #222;
  margin-bottom: 6px;
}
.group-gap {
  margin-bottom: 40px;
}
.btn.focus,
.btn:focus,
.form-control:focus,
.custom-select:focus,
.custom-select:focus {
  box-shadow: none;
}
.form-control:focus,
.custom-select:focus {
  border: 1px solid #f63240;
}

.btn-group-lg > .btn,
.btn-lg {
  padding: 13px 15px 15px;
  font-size: 16px;
  border-radius: 0;
}
.form-control {
  height: auto;
  padding: 15px;
  font-size: 14px;
  color: #fff;
  border-radius: 0;
  background: #fbbe02;
  border: 1px solid #f63240;
}
.custom-select {
  height: auto;
  padding: 15px;
  font-size: 26px;
  cursor: pointer;
  font-weight: 400;
  color: #000;
  background-color: #fbbe02;
  border: 2px solid #000;
}
.custom-control-input:checked ~ .custom-control-label::before {
  border-color: #e91e63;
  background-color: #e91e63;
}
.custom-control-input:focus ~ .custom-control-label::before {
  box-shadow: none;
}
.custom-control-label {
  cursor: pointer;
}
.error:focus,
.error {
  border-color: #e91e63;
  color: #e91e63;
}
.invalid-feedback {
  color: #e91e63;
}
.btn-danger,
body .btn-danger:hover {
  background: #f63240;
  border-color: #f63240;
  color: #fff;
}

Test Select Dropdown in Angular

The context of the last step is to tell you how to start the angular development server; make sure to invoke the given command.

ng serve

You can take help of given command to open the app in the browser.

http://localhost:4200

By using the following command, you may also start the app on the browser directly.

ng serve --ooen

Angular 13 Select Dropdown with Reactive Forms Examples

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.