Build Select Dropdown in Angular 13 with Reactive Forms

Last updated on: by Digamber
Angular 13 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 13

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.

PropertyDetails
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 13 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

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.css']
})
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.css'],
})
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>

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.