0

I have a project that has a select of several questions and I would like the first one to appear by default.

I have seen an example of how to achieve this using the index, of the type:

<select>
 <option *ngFor="let answer of answers; let i = index" [value]="answer.id" [selected]="i == 2">
  {{answer.name}}
 </option> 
</select>

and it works, but when I want to bind the select to a property of the component, it is no longer selected:

<select  [(ngModel)]=searchterms.answerId>
 <option *ngFor="let answer of answers; let i = index" [value]="answer.id" [selected]="i == 2">
  {‌{answer.name}}
 </option> 
</select>

You can see an example here:

https://stackblitz.com/edit/angular-rv9vqi

As say in some answers the solution is to set a default value to the serachterm, but the problem I have, (I am not able to reproduce it in the playground) is that I receive those answers from a service that asks to a back, and when the component is built it still does not have them and it gives me an error .... how can I make it assign those searchterms the value once they exist in the service?

3 Answers 3

5

You can use Angulars two-way data binding to bind to the value attribute of the <select> element. In your example it would look like this:

<select [(value)]="searchterms.answerId">  
    <option *ngFor="let answer of answers" [value]="answer.id">{{answer.name}}</option>  
</select>

Notice how binding to the value attribute cleans up the option element, by enabling you to remove the [selected]="i == 2" and let i = index

However, like the others have mentioned you will want to initialize the desired default value in your component code.

Here is the working StackBlitz Demo with your code

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

Comments

0

You need to set the searchterms.answerId with a proper default value. In your case

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  answers = [
    {name: "Answer 1", id: '1'},
    {name: "Answer 2", id: '2'},
    {name: "Answer 3", id: '3'},
    {name: "Answer 4", id: '4'},
  ];
  searchterms = {
    answerId: this.answers[1].id //Set the default value properly
  };
}

stackblitz

Comments

0

Then you should bind searchterms in your component.

you can do it inside constructor as follows.

this.searchterms.answerId = this.answers[1].id;

Demo

Comments

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.