Angular Material – How to set Default Value in Select Dropdown?

Here, i will show you angular material select dropdown default value. We will use how to set default value in angular material select dropdown. We will look at example of how to set default value in select dropdown in angular material. let’s discuss about set default value in mat-select angular. Let’s get started with angular material select dropdown default value.

You can set default value in material select dropdown in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12 and angular 13.

I will give you simple example of how to set default value in select dropdown in angular material. here you can see ts file code and html file code as bellow:

Let’s see bellow example code here:

src/app/app.component.ts

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

import { FormBuilder, FormGroup, Validators} from '@angular/forms';

interface Website {

value: string;

viewValue: string;

}

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent{

title = 'app-material3';

selectedOption = '2';

websites: Website[] = [

{value: '1', viewValue: 'ItSolutionStuff.com'},

{value: '2', viewValue: 'HDTuto.com'},

{value: '3', viewValue: 'Nicesnippets.com'},

{value: '4', viewValue: 'laravel.com'},

{value: '5', viewValue: 'npm.com'},

{value: '6', viewValue: 'google.com'}

];

form: FormGroup = new FormGroup({});

constructor(private fb: FormBuilder) {

this.form = fb.group({

website: [this.selectedOption, [Validators.required]],

})

}

get f(){

return this.form.controls;

}

submit(){

console.log(this.form.value);

}

}

src/app/app.component.html

<h1>Angular Material Multi Select Box with Default Value Example - ItSolutionStuff.com</h1>

<form [formGroup]="form" (ngSubmit)="submit()">

<mat-form-field>

<mat-label>Select Website</mat-label>

<mat-select formControlName="website" >

<mat-option *ngFor="let website of websites" [value]="website.value">

{{website.viewValue}}

</mat-option>

</mat-select>

<mat-error *ngIf="form.get('website')?.hasError('required')">

Please select website

</mat-error>

</mat-form-field>

<button mat-raised-button color="accent">Submit</button>

</form>

Output:

Angular Material - How to set Default Value in Select Dropdown?

I hope it can help you…

Leave a Comment