Search code examples
angularhtml-selectngforangular-forms

Angular 4 selected not working in option with *ngFor


<option [selected]="true"> is not working in Angular 4 if it is also present an ngFor.

Template:

<form [formGroup]='myForm'>

  <div class="col-sm-9 col-md-4">
    Not working selected, with ngFor
    <select formControlName="nationality" class="form-control">
      <option *ngFor="let elem of nationalityList" [ngValue]="elem.code" [selected]="elem.code=='ITA'">{{ elem.description}}</option>
    </select>
  </div>

  <div class="col-sm-9 col-md-4">
    Working selected, without ngFor
    <select formControlName="nationality" class="form-control">
      <option [ngValue]="nationalityList[0].code" [selected]="nationalityList[0].code=='ITA'">{{ nationalityList[0].description}}</option>
      <option [ngValue]="nationalityList[1].code" [selected]="nationalityList[1].code=='ITA'">{{ nationalityList[1].description}}</option>
    </select>
  </div>

</form>

Component:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: 'app-prova',
  templateUrl: './prova.component.html',
  styleUrls: ['./prova.component.css']
})
export class ProvaComponent implements OnInit {

  myForm:FormGroup = new FormGroup({
    nationality: new FormControl('')
  });

  nationalityList = [
    { description: 'NATIONALITY_ITALIAN', code: 'ITA' },
    { description: 'NATIONALITY_FOREIGN', code: 'EST' }
  ];

  constructor() { }

  ngOnInit() {
  }

}

Output:

enter image description here

So the question is: why doesn't selected work with ngFor? Is it a bug or am I missing something? How to make it work? Thanks.


Solution

  • You should not use selected, try this:

    <form [formGroup]="myForm">
      <select formControlName="nationality" class="form-control">
        <option *ngFor="let elem of nationalityList" [ngValue]="elem.code">
          {{ elem.description}}
        </option>
      </select>
    </form>
    

    And change your myForm definition to:

    myForm:FormGroup = new FormGroup({
      nationality: new FormControl('ITA')
    });