Set Default Value In Select Option Angular

4 min read

Setting a default value in a <select> element is a common requirement when building Angular applications. That said, whether you are working with template‑driven forms, reactive forms, or a third‑party dropdown library, Angular provides several mechanisms to pre‑select an option when the component initializes. This guide walks through the most reliable approaches, explains the underlying concepts, and offers practical examples you can copy into your projects Worth keeping that in mind..

Introduction

Angular’s form handling system treats <select> controls like any other input field. To show a default value you must bind the control’s model to a specific option’s value before the view is rendered. If the model does not match any option’s value, Angular will either leave the dropdown blank or throw an error, depending on the form type. Understanding how Angular compares values and how you can customize that comparison is key to setting defaults correctly Worth knowing..

Methods for Setting a Default Value

1. Template‑Driven Forms

Template‑driven forms rely on ngModel to create a two‑way binding between the component class and the template. The default value is simply the initial value you assign to the bound property.

Step‑by‑step

  1. Declare the model property in the component class and give it an initial value.
  2. Bind the <select> to that property using [(ngModel)].
  3. Provide options with static [value] attributes or via *ngFor.
  4. Optional: Supply a name attribute so Angular can register the control with the form.

Example

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-demo',
  templateUrl: './app.component.html'
})
export class DemoComponent {
  // 1. 

```html

Selected: {{ selectedCountry }}

// In the same component or a service
countries = ['USA', 'Canada', 'Mexico', 'Brazil'];

When the view loads, Angular evaluates [(ngModel)]="selectedCountry" and sees that the model equals 'Canada'. It then marks the <option> with [value]="'Canada'" as selected.

Why it works

  • Angular’s NgModel directive performs a strict equality check (===) between the model value and each option’s [value].
  • Because we initialized selectedCountry with a string that exactly matches one of the option values, the match succeeds on the first change detection cycle.

2. Reactive Forms

Reactive forms expose a FormControl instance that you can manipulate programmatically. Setting a default value is as easy as initializing the control with a value or calling setValue/patchValue after the control is created.

Step‑by‑step

  1. Import ReactiveFormsModule in your module.
  2. Create a FormGroup and add a FormControl for the <select>.
  3. Initialize the control with the desired default value.
  4. Bind the form group to the template using [formGroup] and link the control with formControlName.
  5. Render options using *ngFor and [value].

Example

// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-demo-reactive',
  templateUrl: './app.component-reactive.

  constructor(private fb: FormBuilder) {
    // 3. Set default value while creating the control
    this.form = this.fb.

```html

Selected: {{ form.get('country')?.value }}

Alternative: Setting after creation

If you need to determine the default value dynamically (e.g., after an HTTP request), you can call setValue or patchValue inside ngOnInit or a subscription:

ngOnInit() {
  this.http.get('/api/user').subscribe(user => {
    this.form.patchValue({ country: user.preferredCountry });
  });
}

3. Using compareWith for Complex Objects

When your <select> options are objects (instead of primitive strings or numbers), Angular’s default strict equality (===) will rarely match because two distinct object instances are never equal, even if they contain the same data. The compareWith function tells Angular how to determine equality between the model value and each option The details matter here. That's the whole idea..

Short version: it depends. Long version — keep reading Simple, but easy to overlook..

Step‑by‑step

  1. Define an array of objects for the options.
  2. Create a model property that holds the selected object (or its identifier).
  3. Implement a compare function that returns true when two objects should be considered the same (commonly by comparing an id field).
  4. Bind the function to the <select> via [compareWith].

Example

// app.component.ts
import { Component } from '@angular/core';

interface Country {
  id: number;
  name: string;
}

@Component({
  selector: 'app-demo-compare',
  templateUrl: '.Think about it: /app. component-compare.

  // Default to the object with id === 2 (Canada)
  selectedCountry: Country = this.countries.Even so, find(c => c. id === 2)!

  // Compare by id
  compareById(c1: Country, c2: Country): boolean {
    return c1 && c2 ? Which means c1. id === c2.
New and Fresh

New Arrivals

Branching Out from Here

Continue Reading

Thank you for reading about Set Default Value In Select Option Angular. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home