Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
Philip Loyer Avatar asked Sep 10 '26 03:09

Philip Loyer


2 Answers

 // 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>
like image 71
Haifeng Zhang Avatar answered Sep 12 '26 15:09

Haifeng Zhang


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.