Angular – The correct method to set a default selected option using the mat-select component

angularangular-materialangular-material-6

Using Angular 2 and Angular Material 6.4.7

I need to set a default selected option using the mat-select component.

The following code works as it should and sets the default value when I do not use the [formControl] binding.

example below:

<mat-form-field>
    <mat-select [(value)]="currentYear" placeholder="Select A Year" [formControl]="year.get('year')" >
        <mat-option *ngFor="let y of yearsArr;" [value]="y">{{ y }}</mat-option>
    </mat-select>
</mat-form-field>

The current year (currentYear) is a variable that gets set the value of the current year.

However when I use the form control binding it fails to set the default option on the mat-select component.

example below:

<mat-form-field>
    <mat-select [(value)]="currentYear" placeholder="Select A Year" [formControl]="year.get('year')" >
        <mat-option *ngFor="let y of yearsArr;" [value]="y">{{ y }}</mat-option>
    </mat-select>
</mat-form-field>

I searched stack overflow and came across this solution which works however I get a warning in the browsers console, I'm not sure if this is the correct method of achieving this.

example below:

<mat-form-field>
    <mat-select [(ngModel)]="currentYear" placeholder="Select A Year" [formControl]="year.get('year')" >
        <mat-option *ngFor="let y of yearsArr;" [value]="y">{{ y }}</mat-option>
    </mat-select>
</mat-form-field>

The warning I get is below:

It looks like you're using ngModel on the same form field as
formControl. Support for using the ngModel input property and
ngModelChange event with reactive form directives has been
deprecated in Angular v6 and will be removed in Angular v7.
For more information on this, see our API docs here: https://angular.io/api/forms/FormControlDirective#use-with-ngmodel

I have read the above output, but still can't understand how to fix this.

Any help to clarify or enlighten me on the correct method of achieving this would be greatly appreciated.

Best Answer

The console warning tells you exactly what the issue is, either use the ngModel directive or the formControl directive, not both.

Check this question on how to select a default option with a formControl (it is for a multi select, but it works the same for your case).

Your template code should look something like this:

<mat-form-field>
  <mat-select placeholder="Select A Year" [formControl]="year.get('year')" >
      <mat-option *ngFor="let y of yearsArr;" [value]="y">{{ y }}</mat-option>
  </mat-select>
</mat-form-field>

And in your component you can set the value of your FormControl, i.e. something like this:

ngOnInit() {
  this.year.get('year').setValue(this.currentYear);
}
Related Topic