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])
});
compareThem(o1, o2): boolean{
console.log('compare with');
return o1.name === o2.name;
}
}