Philip Loyer
Philip Loyer

Reputation: 768

How do i implement a data filled dropdown list with Angular 6

I am new to Angular 6, or really just Angular period. I am wanting to place a drop down list on my page which will be populated with values I get from a JSON request else where. How would I go about accomplishing this task?

Upvotes: 3

Views: 10474

Answers (2)

Haifeng Zhang
Haifeng Zhang

Reputation: 31895

 // http request with your server data.
 options$ = this.yourHttpService.getOptions(API);  // returns an Observable

Assume the JSON format is(we will invoke option.value int HTML):

{
    value: 'Option1',
    otherValue: '....'
}

In your html file, populate the options with async:

    <select [(ngModel)]="yourOption" id="category">
       <option value="" disabled selected>>select an option</option>
       <option *ngFor="let option of options$ | async" [value]="option.value">{item.category}}</option>
     </select>

Upvotes: 4

Shan-Desai
Shan-Desai

Reputation: 3349

Assuming your data that needs to be put in the dropdown list is actually an array:

 myData = {data: [v1, v2, v3, v4]};

In your component.html

<select>
  <option *ngFor="let eachVal of myData['data']>
          {{eachVal}}
  </option>
</select>

should do the trick.

Since you do not provide your code snippet, I have a stackBlitz example that uses select and option tags with Angular. Have a look at them.

Upvotes: 1

Related Questions