Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default option in mat-select

I have a simple select option form field in my Angular material project:

component.html

  <mat-form-field>     <mat-select [(value)]="modeSelect" placeholder="Mode">       <mat-option value="domain">Domain</mat-option>       <mat-option value="exact">Exact</mat-option>     </mat-select>   </mat-form-field> 

Where [(value)]="modeSelect" is binded to the modeSelect property in the component.ts file

I want to make it so the <mat-option value="domain">Domain</mat-option> is selected by default on page load.

ng-selected did not work for me

like image 773
cup_of Avatar asked Jun 01 '18 20:06

cup_of


2 Answers

Working StackBlitz

No need to use ngModel or Forms

In your html:

 <mat-form-field>   <mat-select [(value)]="selected" placeholder="Mode">     <mat-option value="domain">Domain</mat-option>     <mat-option value="exact">Exact</mat-option>   </mat-select> </mat-form-field> 

and in your component just set your public property selected to the default:

selected = 'domain';

like image 180
Narm Avatar answered Oct 04 '22 14:10

Narm


This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.

In the "ngOnInit" lifecycle hook

1) Get the object you want to set as the default from your array or object literal

const countryDefault = this.countries.find(c => c.number === '826'); 

Here I am grabbing the United Kingdom object from my countries array.

2) Then set the formsbuilder object (the mat-select) with the default value.

this.addressForm.get('country').setValue(countryDefault.name); 

3) Lastly...set the bound value property. In my case I want the name value.

<mat-select formControlName="country">    <mat-option *ngFor="let country of countries" [value]="country.name" >           {{country.name}}    </mat-option> </mat-select> 

Works like a charm. I hope it helps

like image 44
Darren Street Avatar answered Oct 04 '22 15:10

Darren Street