0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
<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>

2 Comments

If I use this, how do I get the selected value upon form submission?
put in a ngModel in the select component. dev.to/jwp/angular-validation-using-ngmodel-55gf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.