Skip to main content

Bind Select DropDown List in Angular 8

Angular 8.0 is out and earlier I posted about creating an Angular 8 app with Visual Studio 2019, which will help you to get started with Angular 8. In this post, we’ll see how to bind select dropdown list in Angular 8 app by extending the same app.

Bind Select DropDown List in Angular 8

If you want to learn all of Angular, I want to personally recommend ng-book as the single-best resource out there. You can get a copy here. The book is updated to Angular 8.

In this app, there is an angular component fetchdata.component, which calls a server-side ASP.NET Core based API to get a random list of weather forecasts. The API response is shown in a tabular format.

Bind Select DropDown List in Angular 8

Before we add a dropdown, let’s first fix the date format issue in the grid. We can easily fix this by adding a datePipe.

<tbody>
  <tr *ngFor="let forecast of forecasts">
    <td>{{ forecast.date | date:'medium' }}</td>
    <td>{{ forecast.temperatureC }}</td>
    <td>{{ forecast.temperatureF }}</td>
    <td>{{ forecast.summary }}</td>
  </tr>
</tbody>

This is the result. The date is formatted and readable as well.

Bind Select DropDown List in Angular 8

Let’s add a dropdown on top of the grid to filter the data based on the selected value. First, we need to expose an API which returns the weather forecasts list. Below is the code of the new API GetSummaries().

private static string[] Summaries = new[]
{
     "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

[HttpGet("[action]")]
public string[] GetSummaries()
{
    return Summaries;
}

Next is the updated code of fetchdata.component.ts. The constructor now also calls the GetSummaries API, along with WeatherForecasts API and the same result is also stored in cacheForecasts object. We’ll use this object while filtering the data.

There is also a method defined filterForeCasts which gets called on change event of the dropdown. This method filters the forecasts list based on the selected value and then returns the result. Highlighted code in the below snippets is the newly added code to the fetchdata.component.ts.

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
    public forecasts: WeatherForecast[];
    public cacheForecasts: WeatherForecast[];
    public summaries: any[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => {
        this.forecasts = result;
        this.cacheForecasts = result;
    }, error => console.error(error));

      http.get<any[]>(baseUrl + 'weatherforecast/GetSummaries').subscribe(result => {
        this.summaries = result;
      }, error => console.error(error));
    }

    filterForeCasts(filterVal: any) {
        if (filterVal == "0")
            this.forecasts = this.cacheForecasts;
        else
            this.forecasts = this.cacheForecasts.filter((item) => item.summary == filterVal);
    }
}

interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

interface Summary {
    name: string;
}

Lastly, put this HTML in fetchdata.component.html to show the summary dropdown. As you can see here, the filterForeCasts method is called on the dropdown change event to filter the weather forecasts based on the selected value.

<p>This component demonstrates fetching data from the server.</p>

<div>
  <label>Summary: </label>
  <select (change)="filterForeCasts($event.target.value)">
    <option value="0">--All--</option>
    <option *ngFor="let summary of summaries" value={{summary}}>
      {{summary}}
    </option>
  </select>
</div>

<p *ngIf="!forecasts"><em>Loading...</em></p>

Run the application and navigate to fetch data. You should see a dropdown having a list of weather summary. Changing the selection will also update the weather forecast grid.

Bind Select DropDown List in Angular 8

That’s it.

If you really want to master Angular 8, ng-book is the single-best resource out there. Get your copy here at 20% discount.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

4 thoughts to “Bind Select DropDown List in Angular 8”

  1. Thanks for this tutorial!

    Can you please explain where you are providing the value for baseurl? Let’s say if I were creating a mock request to an external service like mocky.io, I would have to provide a base url like ‘mocky.io’. Can you advise? Many thanks

  2. tried this in my code but its not working.
    in line no 28
    this.forecasts = this.cacheForecasts.filter((item) => item.summary == filterVal);
    getting error as “Reference error: item is not defined”. could you help me in fixing this…

Leave a Reply

Your email address will not be published. Required fields are marked *