Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 998
Jeyabalan Thavamani Avatar asked Jan 02 '23 09:01

Jeyabalan Thavamani


1 Answers

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;
  }
}
like image 70
Aragorn Avatar answered Jan 13 '23 15:01

Aragorn