1

How to show actual selected option from dropdown list and after stretching the list other available elements. Now I have the dropdownlist with only avaible elements which i can choose element. HTML:

        <div class="pb-1">
          <label class="small">Car:</label>
          <select formControlName="Car" class="form-control">
              <option *ngFor="let x of cars" [ngValue]='x.id'>{{x.id}} : {{x.carName}}</option>
          </select>
        </div>

TypeScript:

export class PersonDetailsComponent implements OnInit {
 cars : Car[];
.
.
.
populateCars()
{
  this.personsService.getCars().subscribe(result => {
    this.cars = result;
});
}

personsService:

getCars() :Observable<Car[]>
    {  
        return this.http.get(this.apiUrl + 'AviableCars')
                        .map((result)=>result.json());
    };
voltdev
  • 260
  • 1
  • 4
  • 9

1 Answers1

1

You need to use the [selected] attribute. I would also add a "Please select" default option:

<option value="" disabled selected> <!-- default selected -->
  Please select a car
</option>
<option *ngFor="let x of cars" [ngValue]='x.id' [selected]="Car.id === x.id">
  {{x.id}} : {{x.carName}}
</option>

The [selected] attribute requires an expression that evaluates to true or false. If true it will highlight that item (x.id) in the list.

So here it is checking that the Car.id (from your model) matches x.id in the *ngFor - so the expression will be evaluated for each x in the ngFor, and one of them of course should be true.

More info here and here

rmcsharry
  • 5,363
  • 6
  • 65
  • 108