Set Default Value of Dropdown | Angular


Set Default Value of Dropdown in Angular.

Let’s have a look at how you can set default value in Angular dropdown.

Template Driven Forms

While using template driven forms, let’s say your app.component.html looks like:

<mat-select placeholder="Select price" [(ngModel)]="selectedValue" name="item">
  <input [(ngModel)]="searchTxt" matInput placeholder="search">
  <mat-option *ngFor="let item of items | search : searchTxt" [value]="item.value">
    {{item.viewValue}}
  </mat-option>
</mat-select>

Here is how the app.component.ts file looks:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  selectedValue: any;
  searchTxt: any;

  items = [{
    value : 100,
    viewValue : 100
  },{
    value : 200,
    viewValue : 200
  },{
    value : 300,
    viewValue : 300
  }];

  ngOnInit(){
    
  }

}

To set the default value to the dropdown, you need to set the value of the variable selectedValue. Let’s say you want to set the first item of items as default, inside ngOnInit add the following:

ngOnInit() {
    this.selectedValue = this.items[0].value;
}

Reactive Forms

If you are using Reactive Forms, assuming your app.component.html looks like :

<div [formGroup]="formGroup">
  <mat-select formControlName="itemCtrl" placeholder="Select price" name="item">
    <input [(ngModel)]="searchTxt" matInput placeholder="search">
    <mat-option *ngFor="let item of items | search : searchTxt" [value]="item.value">
      {{item.viewValue}}
    </mat-option>
  </mat-select>
</div>

Here is how your app.component.ts file looks:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  selectedValue: any;
  searchTxt: any;

  items = [{
    value : 100,
    viewValue : 100
  },{
    value : 200,
    viewValue : 200
  },{
    value : 300,
    viewValue : 300
  }];

  formGroup : FormGroup;

  constructor(private fb : FormBuilder){}

  ngOnInit() {
    this.formGroup = this.fb.group({
      itemCtrl : ['']
    });
  }
}

To set the default value of the dropdown while using reactive forms, add the following code to ngOnInit

  ngOnInit() {
    this.formGroup = this.fb.group({
      itemCtrl : ['']
    });
    this.setDefaultValue();
  }

  setDefaultValue(){
    this.formGroup.patchValue({
      itemCtrl : this.items[1].value
    })
  }