Build Select Dropdown in Angular 16 with Reactive Forms

Last Updated on by in Angular
Angular 16 Select Dropdown Tutorial with Reactive Forms is going to be discussed today. We will learn to work with Select dropdown in Angular with Reactive Forms.We are going to create and validate select dropdown HTML element using Reactive forms.

SelectControlValueAccessor Directive in Angular

Before, we begin we need to understand what ControlValueAccessor is.

Well, this directive allows us to work with a select dropdown HTML element. It observes any changes made in select dropdown value.

It works with the help of FormControlDirective, FormControlName, and NgModel directive.

Property Details
onChange() It’s an official function, It works when any change event occurs on the HTML input.
onTouched() It’s an official function, It triggers when a blur event occurs on the HTML input.
@Input() It’s a write only event, It tracks the option comparison algorithm for tracking identities when checking for changes.

Angular 16 Select Dropdown Example

  • Configure Reactive Forms Select Dropdown
  • Configure Select Dropdown
  • Choose Multiple Values in Select Dropdown
  • On Change Angular Select Option Change
  • Angular Select Dropdown Custom Validation with Reactive

Create New Angular Project

Run command to set up a basic Angular project:

ng new angular-demo

Answer angular CLI questions:

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose SCSS and hit Enter

Then, step inside the project folder:

cd angular-demo

No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
}

Configure Reactive Forms Select Dropdown Demo

I assume you’ve already set up a basic Angular project to work with select dropdown, now in order to work with Reactive forms you must import ReactiveFormsModule in app.module.ts file.

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

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})

Configure Select Dropdown

For the demo purpose, I am going to create a list of Oppo suits and save it in the array, then i will manipulate the values of Oppo suits with Angular select dropdown HTML element.

Create a basic Reactive form to work with select dropdown in Angular.

app.component.ts

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

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

export class AppComponent {
  oppoSuits: any = ['Men', 'Women', 'Boys', 'Inspiration']

  constructor(public fb: FormBuilder) { }

  oppoSuitsForm = this.fb.group({
    name: ['']
  })

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

app.component.html

<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()">

  <select formControlName="name">
    <option disabled>Select Oppo Suits</option>
    <option>Choose oppo suit</option>
    <option *ngFor="let suit of oppoSuits">{{suit}}</option>
  </select>

  <button>Submit</button>
</form>

Choose Multiple Values via Select Dropdown

Selecting multiple values with Select Dropdown is not that difficult we have to pass the multiple tag with the <select multiple> HTML input.

<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()">

  <select multiple formControlName="name">
    <option disabled>Select Oppo Suits</option>
    <option>Choose oppo suit</option>
    <option *ngFor="let suit of oppoSuits">{{suit}}</option>
  </select>

  <button>Submit</button>
</form>

Select Dropdown Change Detection

In this part of the tutorial, we are going to work with change event with Select Dropdown in Angular. We will use (change)="" event to detect the change in select dropdown.

app.component.html

<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()">

  <select formControlName="name" (change)="changeSuit($event)">
    <option value="">Choose oppo suit</option>
    <option *ngFor="let suit of oppoSuits">{{suit}}</option>
  </select>

  <div class="error-block" *ngIf="submitted && handleError('name', 'required')">
    You must provide a value!
  </div>

  <button>Submit</button>
</form>

As you can see, I’ve connected the changeSuit() function with (change) event. So, whenever the select dropdown value changes changeSuit() function will be called.

$event: This value refers to the payload of the selected dropdown element.

app.component.ts

changeSuit(e) {
  this.oppoSuitsForm.get('name').setValue(e.target.value, {
     onlySelf: true
  })
}

Angular Custom Validation for Select Dropdown

To validate the select dropdown in Angular, we need to import Validators class with Reactive Forms.

I am also going to create a custom validators function for select dropdown validation using Reactive forms, we can also use this custom validator to validate other Form elements as well.

Go to app.component.ts file and add the following code.

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 {
  submitted = false;
  oppoSuits: any = ['Men', 'Women', 'Boys', 'Inspiration'];

  constructor(public fb: FormBuilder) {}

  oppoSuitsForm = this.fb.group({
    name: ['', [Validators.required]],
  });

  /* Select Dropdown error handling */
  public handleError = (controlName: string, errorName: string) => {
    return this.oppoSuitsForm.controls[controlName].hasError(errorName);
  };

  changeSuit(e) {
    this.oppoSuitsForm.get('name').setValue(e.target.value, {
      onlySelf: true,
    });
  }

  onSubmit() {
    this.submitted = true;
    alert(JSON.stringify(this.oppoSuitsForm.value));
  }
}

Go to app.component.html file and add the following code.

<form [formGroup]="oppoSuitsForm" (ngSubmit)="onSubmit()">

  <select formControlName="name">
    <option value="">Choose oppo suit</option>
    <option *ngFor="let suit of oppoSuits">{{suit}}</option>
  </select>

  <div class="error-block" *ngIf="submitted && handleError('name', 'required')">
    You must provide a value!
  </div>

  <button>Submit</button>
</form>

Run the following command to serve your app locally:

ng serve --open

Open a web browser and navigate to:

 http://localhost:4200/

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.