Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 *ngFor in select list, set active based on string from object

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?

like image 715
Mikkel Avatar asked Feb 19 '16 19:02

Mikkel


People also ask

Does ngFor work on objects?

The ngFor directive accepts any object that implements the Iterable interface. You can read more about iterators here. So, for example, we can create our own iterable and just give it to the ngFor directive.

Why * is used in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag.

Can we use ngFor in UL tag?

Angular2: <li> with *ngFor not inside <ul> The <ul> tag is not filled by those <li> tag created by *ngFor which makes the "line" of the timeline disappear. The black border is the border of the <ul> tag, which is suppose to wrap all <li> tags below it and have the magenta line go through all bubbles.


2 Answers

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.

like image 94
Günter Zöchbauer Avatar answered Oct 10 '22 02:10

Günter Zöchbauer


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")];  } 
like image 38
acdcjunior Avatar answered Oct 10 '22 00:10

acdcjunior