tobi
tobi

Reputation: 13

Why can't I mark an option in Angular as selected?

I have following code for my dropdown menu. How can I set a value as selected?

<div class="input-group mb-3">
  <label class="input-group-text labelDropDown" for="inputGroupSelect01">Art der
    Integration</label>
    <select class="form-select" id="inputGroupSelect01" formControlName="integrationType">
    <option value="statisch">statisch</option>
    <option value="dynamisch">dynamisch</option>
    <option value="nein">nein</option>
  </select>
</div>

I thought it will be selected if I type in the selected keyword? Why does angular not do this?

Upvotes: 0

Views: 152

Answers (3)

Andriu1510
Andriu1510

Reputation: 409

I think this work for you:
Use selected in the <option> tag

<div class="input-group mb-3">
  <label class="input-group-text labelDropDown" for="inputGroupSelect01">Art der
    Integration</label>
 <select class="form-select" id="inputGroupSelect01" formControlName="integrationType">
     <option value="statisch">statisch</option>
     <option value="dynamisch">dynamisch</option>
     <option value="nein" selected>nein</option>
  </select>
</div>

Upvotes: 2

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

The selected value is defined by the formControl you bound it to. Once you give the FormControl integrationType a value, this value will be selected. If you set nein as it's value, the 3rd option neinwill be selected.

Example edit value after init

this.myFormGroup.get('integrationType').setValue('nein');

Example with value on init

this.myFormGroup = this.formBuilder.group({
      integrationType: ['nein'],
    });

Upvotes: 0

Ch1ll1_K
Ch1ll1_K

Reputation: 13

Selected is an boolean parameter from the HTML Element select so you have set it to true for the specific option element. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

Alternative Solutions: use selectedHTMLEl.selectedIndex

sets the selected Option by the Index of Option

Upvotes: 0

Related Questions