Reputation: 1183
I have a list of types in my component.ts as followed.
public type: string;
types:Array<Object> = [
{name: "Category", value: "c"},
{name: "Cuisine", value: "a"},
{name: "Main Ingredient", value: "i"},
];
And here is the corresponding HTML code.
<select class="form-control" id="queryTypeSelect" [(ngModel)]="type" name="queryTypeSelectForm">
<option *ngFor="let typ of types" [value]="typ.value">{{ typ.name }}</option>
</select>
In the constructor, I have initialized "type" like this:
constructor(
private recipeService: RecipeService,
private apiService: ApiService) {
this.type = this.types[0]["name"];
}
But when loading the page, the select bar shows nothing, until I manually select something. Although when selecting, the default item shows as checked (the first entry).
Why is this happening? When I remove the value property from the option, it shows the default entry alright. But I need to have the value property.
What is going wrong here? Any kind of help would be appreciated.
Upvotes: 0
Views: 49
Reputation: 6963
<select class="form-control" id="queryTypeSelect" name="queryTypeSelectForm">
<option *ngFor="let typ of types"
[selected]="typ.name === type"
[ngValue]="typ.value"
>{{ typ.name }}</option>
</select>
Upvotes: 0
Reputation: 172
In your constructor, you should use
this.type = this.types[0]["value"];
Angular Forms will compare ther Selects ngModel with each options [value] to select the preselected option.
While you use types[0]["name"]
, Angular has no chance to match your preselected value with the correct option.
Upvotes: 1