How to set value in angular mat-select when component loading?

12,901

Solution 1

Use compareWith to select the default value by comparing the name inside the compare function. Also note, I've changed value binding to [(value)] ="animal". And removed selectedValue. You select the default by assigning it in the formControl, look below changes in the component.

<form [formGroup]="myGroup">
<mat-form-field>
  <mat-select placeholder="Favorite animal" [compareWith]="compareThem" formControlName="animalControl" required >
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [(value)] ="animal"  >
      {{animal.name}}
    </mat-option>
  </mat-select>
</mat-form-field>
</form>

In your component, add:

export class AppComponent  {

  animals = [
    {name: 'Dog', sound: 'Woof!'},
    {name: 'Cat', sound: 'Meow!'},
    {name: 'Cow', sound: 'Moo!'},
    {name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
  ];  

  myGroup = new FormGroup({
      animalControl: new FormControl(this.animals[1], [Validators.required]) //I'm assigining Cat by using this.animals[1], you can put any value you like as default.
  });


  compareThem(o1, o2): boolean{
    console.log('compare with');
    return o1.name === o2.name;
  }
}

Solution 2

Thilagabahan, if the [value] is animals.name

<mat-option *ngFor="let animal of animals" [value]="animal.name">

simply, when you create the form, give the value (else take a look Aragom's answer)

    selectedValue = this.animals[0].name;
    myGroup = new FormGroup({
      animalControl: new FormControl(this.selectedValue, [Validators.required])
  });

See that the last one is create the formGroup

Share:
12,901
Jeyabalan Thavamani
Author by

Jeyabalan Thavamani

Updated on June 08, 2022

Comments

  • Jeyabalan Thavamani
    Jeyabalan Thavamani almost 2 years

    I used angular material("@angular/material": "7.1.0") mat-select box and then i used form control instead of ng model, now the problem is i can't set the value when the component is loading. I need to set the first value to mat-select box from the list, i tried but i cant do that.

    I have created a code at stackblitz, here is the link: https://stackblitz.com/edit/angular-zt1a9f

    please help me on that.

  • Eliseo
    Eliseo over 5 years
    @Aragom, you has [ngValue]="animal.name", must be [ngValue]="animal"