CountZero CountZero - 1 year ago 212
TypeScript Question

Angular 2 - Setting selected value on dropdown list

I have run into an issue in pre-selecting values on a dropdown list in Angular 2.

I set an array of colours in the component which I bind successfully to the dropdown list. The issue I'm experiencing is with pre-selecting a value on page init.

The line '[selected]=" =="' should be selecting the value which has been set on the car model ' = new Colour(-1,'');' however this only works when I set the car colour id to the last item in the list (in this case black) ' = new Colour(4,'');'

I am using the latest version of Angular (rc3) and have experienced the same issues in rc1 and rc2.

Here is a plunker showing the issue.

Another odd aspect is that when looking at the meta data Angular has set the selected value to true.

enter image description here

But the dropdown still appears empty.

enter image description here

It appears to be a seperate issue from these related questions.

Angular 2 Set begin value of select

Binding select element to object in Angular 2

How to use select/option/NgFor on an array of objects in Angular2



Component template

<select [(ngModel)]="car.colour"">
<option *ngFor="let x of colours" [value]="" [selected]=" ==">{{}}</option>


import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';

export class DropdownComponent implements OnInit
car:Car = new Car();
colours = Array<Colour>();

ngOnInit(): void {

this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.colours.push(new Colour(3, 'Orange'));
this.colours.push(new Colour(4, 'Black')); = new Car(); = new Colour(-1,'');

export class Car

export class Colour
constructor(id:number, name:string) {;;


Answer Source

Setting car.colour to the value you want to have initially selected usually works (especially if colour is a primitive value like number, string, etc.)

When car.colour is set, you can remove [selected]=" ==".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download