Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"selected" tag on option doesn't work when select has formControlName

Tags:

select

angular

<div class="form-inline">
  <label class="text-color">Lokalizacja:</label>
  <select class="form-control dropdown" formControlName="localization">
    <option value="Gdańsk" selected>Gdańsk</option>
    <option value="Rzeszów">Rzeszów</option>
    <option value="Wrocław">Wrocław</option>
  </select>
</div>

Don't know what happened but in that case there is no selected option and I have to choose something from the list. When I delete formControlName="localization from select, then Gdańsk is selected at the start.

Lokalization control looks like this localizationCtrl = new FormControl("", Validators.required);

there is no difference when I replace that on: localizationCtrl = new FormControl(""); of course next step was to add that control to offerForm by doing:

...
localization: this.localizationCtrl
...

but please don't try to look for a problem here because I have something like 7 other validators inside offerForm and all of them work fine.

like image 250
elzoy Avatar asked Feb 07 '23 11:02

elzoy


1 Answers

Assign the default value during form model initialization.

`localizationCtrl = new FormControl("Gdańsk", Validators.required);`

or if the value is coming from the server, use formControl's updateValue method.

localizationCtrl.updateValue('Gdańsk');

See here: https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol and https://scotch.io/tutorials/how-to-deal-with-different-form-controls-in-angular-2

like image 63
Chybie Avatar answered Feb 09 '23 01:02

Chybie