Reputation: 591
I took a Material Select example and tried to set a default value from the ngOnInit method like this:
ngOnInit(): void {
this.animalControl.setValue({name: 'Cat', sound: 'Meow!'});
}
But it is not showing the default value in the select (there is only Meow). I do not know why.
Upvotes: 3
Views: 556
Reputation: 2349
The error here is not due to your FormControl
not being populated correctly on ngOnInit
but yet instead your ngFor filters through the list animals: Animal[]
which have a different reference than your new object {name: 'Cat', sound: 'Meow!'}
, if you instead pass an object within your animal list it will have the correct reference and display the value of the animal name correctly.
Example:
ngOnInit(): void {
this.animalControl.setValue(this.animals[0]);
}
Upvotes: 4
Reputation: 5742
Here is working example
instead passing new object you have to pass your array data
ngOnInit(): void {
this.animalControl.setValue(this.animals[0]);
}
Upvotes: 1
Reputation: 1925
Instead of
this.animalControl.setValue({name: 'Cat', sound: 'Meow!'});
set value of animalFormControl by calling animals array. Update your code by reviewing below implementation
this.animalControl.setValue(this.animals[1]);
Upvotes: 1