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
- Declare the model property in the component class and give it an initial value.
- Bind the
<select>to that property using[(ngModel)]. - Provide options with static
[value]attributes or via*ngFor. - Optional: Supply a
nameattribute 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
// 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
NgModeldirective performs a strict equality check (===) between the model value and each option’s[value]. - Because we initialized
selectedCountrywith 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
- Import
ReactiveFormsModulein your module. - Create a
FormGroupand add aFormControlfor the<select>. - Initialize the control with the desired default value.
- Bind the form group to the template using
[formGroup]and link the control withformControlName. - Render options using
*ngForand[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
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
- Define an array of objects for the options.
- Create a model property that holds the selected object (or its identifier).
- Implement a compare function that returns
truewhen two objects should be considered the same (commonly by comparing anidfield). - 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.