I am creating a select element, and want to set an object as the default value when the application starts. In my example I have a list of animals, and a FormControl used in an HTML template. I tried adding an object (not a reference to an object) directly to the formControl like this:
animalControl = new FormControl({name:'Dog', sound: 'Woof!'}, [Validators.required]); // this does not work
This does not work. However, referencing an object from the actual list works, like this:
this.animalControl.setValue(this.animals[1]); // this works
Is there another way of setting a value to the formControl without having to find the correct reference, only passing an object to it instead?
Working example: https://stackblitz.com/edit/angular-object-default-select?file=app/select-hint-error-example.ts
TS:
export class SelectHintErrorExample {
animalControl = new FormControl({name:'Dog', sound: 'Woof!'}, [Validators.required]); // this does not work
animals = [
{name: 'Dog', sound: 'Woof!'},
{name: 'Cat', sound: 'Meow!'},
{name: 'Cow', sound: 'Moo!'},
{name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
];
constructor(){
// this.animalControl.setValue(this.animals[1]); // this works
}
}
HTML:
<mat-form-field>
<mat-select placeholder="Favorite animal" [formControl]="animalControl" required>
<mat-option>--</mat-option>
<mat-option *ngFor="let animal of animals" [value]="animal">
{{animal.name}}
</mat-option>
</mat-select>
<mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>
<mat-hint>{{animalControl.value?.sound}}</mat-hint>
</mat-form-field>