53

I'm trying using the ngFor on my select DropDownList. Have loaded in the options which should be in the dropdown.

The code you see here:

<div class="column small-12 large-2">
    <label class="sbw_light">Title:</label><br />
    <select [(ngModel)]="passenger.Title">
       <option *ngFor="#title of titleArray" [value]="title.Value">{{title.Text}}</option>
    </select>
</div>

Based on this code, it produces a dropdown which look like this image.

enter image description here

The problem is that I want to set one of them "Mr or Mrs" as the active one based on the passenger.Title which is a string either "Mr" or "Mrs".

Any can help see what I'm doing wrong here?

mpro
  • 14,302
  • 5
  • 28
  • 43
Mikkel
  • 1,771
  • 11
  • 35
  • 59

2 Answers2

94

This should work

<option *ngFor="let title of titleArray" 
    [value]="title.Value" 
    [attr.selected]="passenger.Title==title.Text ? true : null">
  {{title.Text}}
</option>

I'm not sure the attr. part is necessary.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks. Good answer! – Vnuuk Jan 30 '17 at 06:54
  • 1
    Adding the "? true : null" to the [select] attribute is what worked for me. I searched on this for a couple of days. In my case, I'm pulling Asp.Net TimeZone Ids from an API and allowing the user to select the correct one. – Dumber_Texan2 Sep 25 '19 at 17:35
18

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}
acdcjunior
  • 132,397
  • 37
  • 331
  • 304