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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With