Create Select Dropdowns in Angular 16 using Reactive Forms

Last Updated on by in Angular

In this tutorial, we will learn how to create select dropdown list in Angular. To build the create dropdown list in Angular you need to set up Angular forms API in the AppModule class.

Not just that, we will demystify the process of how to build single and multi select dropdown in Angular. On top of that, we will show how to integrate validation in angular select dropdown list component.

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

Run command 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 Project

Now the angular CLI is installed, now, install the new 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

Remove Angular TypeScript Errors

To get rid from the errors:

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 following properties to false in tsconfig.json file:

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

Add Reactive Forms API

In this step, import the ReactiveFormsModule as well as FormsModule API.

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 { FormsModule, ReactiveFormsModule } from '@angular/forms';

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

export class AppModule { }

Install Bootstrap Module

Bootstrap offers ready-made UI components, you can use the Bootstrap CSS to style the select dropdown in Angular.

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));
    }
  }
}

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 Select Dropdown with Reactive Forms Examples

Conclusion

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

Throughout Angular select dropdown tutorial, we went through the various HTML code example for Angular select box.

The primary Idea of this tutorial was to help angular developer understand the entire concept of implementing select dropdown in angular application.

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.