I have this form group with several form controls:
myForm: FormGroup = new FormGroup({
...
myControl: new FormControl(),
...
});
The form control myControl
is this:
<mat-form-field class="col-large">
<mat-select formControlName="myControl">
<mat-option *ngFor="let data of dataMap" [value]="data.value">
{{data.description}}
</mat-option>
</mat-select>
</mat-form-field>
The dataMap
is basically an array of objects that have a property value and a property description, both of them are strings, so an example of object is:
{
"value":"1",
"description":"desc"
}
Then I have an autocomplete input that works on the same dataMap
and, whenever the user starts typing, it searches through the descriptions of the array, prompting only the ones that matches with the text written. Then, when the user selects an option, it calls a method that retrieves the correspondent value from the array and sets the value retrieved for myControl
. The expected behaviour is that, when an option in the autocomplete is selected, the value is changed in myControl
and a new description is shown.
The problem is that the value for myControl
is correctly set, but no selected option is showed.
What I do not understand is that in the ngOnInit method I set a default value from the map for myControl
this way:
this.myForm.get('myControl').setValue("1");
and it correctly select the option and shows it as selected. Then, in the callback method for the autocomplete selection, I do the same but it is not selected. The form control goes blank.
I've checked the value I get from the autocomplete and it exists in dataMap
. I've also printed the value for myControl
after setting the new value and it is the correct new one.
do this instead
let test = {
"value":"1",
"description":"desc"
}
this.myForm.get('myControl').setValue(test);
you should pass the same type of object to the myControl