Home > Software engineering >  Why can't I mark an option in Angular as selected?
Why can't I mark an option in Angular as selected?

Time:11-30

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

<div >
  <label  for="inputGroupSelect01">Art der
    Integration</label>
    <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?

CodePudding user response:

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

<div >
  <label  for="inputGroupSelect01">Art der
    Integration</label>
 <select  id="inputGroupSelect01" formControlName="integrationType">
     <option value="statisch">statisch</option>
     <option value="dynamisch">dynamisch</option>
     <option value="nein" selected>nein</option>
  </select>
</div>

CodePudding user response:

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

CodePudding user response:

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'],
    });
  • Related