Mathieu Gemard
Mathieu Gemard

Reputation: 591

Cannot set value on a formControl from ngOnInit method

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.

stackblitz

Upvotes: 3

Views: 556

Answers (3)

Tiago Silva
Tiago Silva

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

Chanaka Weerasinghe
Chanaka Weerasinghe

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

varundhariyal
varundhariyal

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

Related Questions