Angular 7|8|9 Select Dropdown Examples with Reactive Forms

By Digamber Rawat Last updated on
In this Angular tutorial, I’m going to share with you how to work with Angular 7|8|9 Select Dropdown. We’ll learn to work with Angular select dropdown with Reactive Forms. In this tutorial i will show you how you can create, implement and validate select dropdown in Angular app.

Understand SelectControlValueAccessor

The SelectControlValueAccessor is very useful directive, 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.

Angular 7|8|9 Reactive Form Setup for Select Dropdown

Inject ReactiveFormsModule in app.module.ts file to work with select dropdown in Angular app.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})

app.component.html

<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">

   <select class="custom-select">
      <option value="" disabled>Choose your city</option>
      <option>New York</option>
   </select>

   <button type="submit">Submit</button>
</form><!-- Form ends -->

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";

@Component({
  // ...
})

export class AppComponent {

  constructor(public fb: FormBuilder) { }

  /*########### Form ###########*/
  registrationForm = this.fb.group({
    cityName: ['']
  })

  onSubmit() {
    alert(JSON.stringify(this.registrationForm.value))
  }

}

Create Select Dropdown in Angular 7|8|9 App

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

// City Names
  City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan']

Go to app.component.html file and add the below select dropdown HTML code. We are iterating our city names array to populate city names in the select dropdown list.

<select class="custom-select" (change)="changeCity($event)" formControlName="cityName">
   <option value="" disabled>Choose your city</option>
   <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
</select>

Bind (change)="" event listener to the changeCity() function. This will add the value dynamically to form control. Since user going to choose value on his choice so we can not pre-filled the value. We’ll use setValue() method to dynamically set the form control value.

 // Choose city using select dropdown
  changeCity(e) {
    this.cityName.setValue(e.target.value, {
      onlySelf: true
    })
  }

Angular 7|8|9 Multiple Select Dropdown

Angular offers SelectMultipleControlValueAccessor directive for selecting multiple options in select dropdown. This directive allows us to write multi-select control values in Angular 7 | 8 forms and also listens to multi-select control changes. Following value accessor can be used by the FormControlName, FormControlDirective, and NgModel directives.

Following code will be used in Angular HTML component.

<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">

   <select multiple formControlName="cityName">
      <option value="">Choose your city</option>
      <option *ngFor="let city of City" [ngValue]="city" (change)="changeCity($event)">{{city}}
      </option>
   </select>

   <!-- error block -->
   <div class="invalid-feedback" *ngIf="isSubmitted && cityName.errors?.required">
      <sup>*</sup>Please enter your city name
   </div>

   <!-- Submit Button -->
   <button type="submit" class="btn btn-danger btn-lg btn-block">Submit</button>
</form><!-- Form ends -->

Below file contains Angular multiple select dropdown logic with form validation.

import { Component } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  isSubmitted = false;

  // City Names
  City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan', 'New York']

  constructor(public fb: FormBuilder) { }

  /*########### Form ###########*/
  registrationForm = this.fb.group({
    cityName: ['', [Validators.required]]
  })

  // Getter method to access formcontrols
  get cityName() {
    return this.registrationForm.get('cityName');
  }

  /*########### Template Driven Form ###########*/
  onSubmit() {
    this.isSubmitted = true;
    if (!this.registrationForm.valid) {
      return false;
    } else {
      alert(JSON.stringify(this.registrationForm.value))
    }

  }

}

Angular Multiple Select Dropdown Demo

Recommended Tutorial

Angular 7|8|9 Select Dropdown Validation

To validate Angular select dropdown, we require to use Validators class with Reactive Forms. I will validate the required value of select options.

Using getter method to access select options’s form control value.

// Getter method to access formcontrols
get cityName() {
  return this.registrationForm.get('cityName');
}

Import Validators class to access form control for form validation.

import { FormBuilder, Validators } from "@angular/forms";

Add the Validators class in form control array.

/*########### Form ###########*/
 registrationForm = this.fb.group({
    cityName: ['', [Validators.required]]
 })

Define the error message in the Angular HTML component.

<select (change)="changeCity($event)" formControlName="cityName">
   <option value="">Choose your city</option>
   <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
</select>

<!-- error block -->
<div *ngIf="isSubmitted && cityName.errors?.required">
   <sup>*</sup>Please enter your city name
</div>

Angular 7|8|9 Select Option Change Event

We are going to use (change)="" event in Angular select; this event triggers when the selection of an item is changed.

<select formControlName="cityName" (change)="changeCity($event)">
   <option value="">Choose your city</option>
   <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
</select>

We’ve bind the changeCity($event) function with (change)="" event. Now changeCity() function will be called whenever the select dropdown’s value changes.

$event: It contains payload of information related to the DOM element.

// Choose city using select dropdown
  changeCity(e) {
    this.cityName.setValue(e.target.value, {
      onlySelf: true
    })
  }

Full Angular 7 Select Dropdown Example

app.component.html

<div class="container">
   <div class="row custom-wrapper">
      <div class="col-md-12">
         <!-- Form starts -->
         <form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
         <div class="group-gap">
            <div class="d-block my-3">
               <div class="mb-3">
                  <select class="custom-select" (change)="changeCity($event)" formControlName="cityName">
                     <option value="">Choose your city</option>
                     <option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
                  </select>
                  <!-- error block -->
                  <div class="invalid-feedback" *ngIf="isSubmitted && cityName.errors?.required">
                     <sup>*</sup>Please enter your city name
                  </div>
               </div>
            </div>
         </div>
         <!-- Submit Button -->
         <button type="submit" class="btn btn-danger btn-lg btn-block">Submit</button>
         </form><!-- Form ends -->
      </div>
   </div>
</div>

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  isSubmitted = false;

  // City Names
  City: any = ['Florida', 'South Dakota', 'Tennessee', 'Michigan']

  constructor(public fb: FormBuilder) { }

  /*########### Form ###########*/
  registrationForm = this.fb.group({
    cityName: ['', [Validators.required]]
  })


  // Choose city using select dropdown
  changeCity(e) {
    console.log(e.value)
    this.cityName.setValue(e.target.value, {
      onlySelf: true
    })
  }

  // Getter method to access formcontrols
  get cityName() {
    return this.registrationForm.get('cityName');
  }

  /*########### Template Driven Form ###########*/
  onSubmit() {
    this.isSubmitted = true;
    if (!this.registrationForm.valid) {
      return false;
    } else {
      alert(JSON.stringify(this.registrationForm.value))
    }

  }

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Final Demo of Angular Select Options with Reactive Forms

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.