Angular Material Autocomplete Dropdown

In this article, we’ll see how to setup angular material autocomplete dropdown.

Angular Material Autocomplete is a normal input but enhanced by panel of suggested options which will popup while searching via input.

Simple Autocomplete

Angular Material Autocomplete Code will look as following:

<mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of options" [value]="option"> {{option}} </mat-option> </mat-autocomplete>

As you can see in the above code, we’ve used mat-autocomplete component of angular material which contains a list of options and we can provide list of options using mat-option. this options will be shown as a popup below when you’ll focus on input.

And the value of the option will be set to value of the text input when the option is selected. so set the value of the option that you would like to set to text input when it’s selected.

Now we’ll create an input and set the matAutocomplete input to refer to the template reference we assigned to the autocomplete which is auto.

And then create formControl and bind this input to the formControl to track the value of the input.

We’ll link input and autocomplete panel by exporting autocomplete panel instance to local template variable(“auto”) and binding that variable to the input’s matAutoComplete property.

So our code will looks like this:

<form class="example-form"> <mat-form-field class="example-full-width"> <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of options" [value]="option"> {{option}} </mat-option> </mat-autocomplete> </mat-form-field> </form>

and our component will look as follows:

import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'autocomplete-simple-example', templateUrl: 'autocomplete-simple-example.html', styleUrls: ['autocomplete-simple-example.css'], }) export class AutocompleteSimpleExample { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; }

If you’ll run the above code the output will look as following, it’ll show the list of options when you’ll focus on input so it’s just togglable and selectable but it won’t filter the input when you type anything. Now we’ll see how to add a custom filter so that the options will be filtered out when you type something in the input.

Output

Angular Material Autocomplete Example

Adding Custom Filter

Now we’ll filter the options when user type something in the input. so what we need to do is on input change we’ll filter the options and will store in in other variable.

so to get the input change event, we already have valueChanges in form control. so we can map the text input’s values to the suggested options by passing them through this filter. The resulting Observable filteredOptions can be added to the template in place of the options property using the async pipe.

so our filter will looks like this:

import {Component, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; import {Observable} from 'rxjs'; import {map, startWith} from 'rxjs/operators'; @Component({ selector: 'autocomplete-filter-example', templateUrl: 'autocomplete-filter-example.html', styleUrls: ['autocomplete-filter-example.css'], }) export class AutocompleteFilterExample implements OnInit { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; filteredOptions: Observable<string[]>; ngOnInit() { this.filteredOptions = this.myControl.valueChanges .pipe( startWith(''), map(value => this._filter(value)) ); } private _filter(value: string): string[] { const filterValue = value.toLowerCase(); return this.options.filter(option => option.toLowerCase().includes(filterValue)); } }

and template file will looks as follwing:

<form class="example-form"> <mat-form-field class="example-full-width"> <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of filteredOptions | async" [value]="option"> {{option}} </mat-option> </mat-autocomplete> </mat-form-field> </form>

Output

Angular Material Autocomplete Example

Now we’ll see advance example of angular material autocomplete with search.

Advance Example

Now, we’ll see angular material autocomplete example.

We’ll see an example of filtering country in angular material autocomplete.

We’ll create date service which returns country data and we’ll use that data in material autocomplete to understand how angular material autocomplete with search works.

Our folder structure will looks as follows:

Angular Material Autocomplete search folder structure

We’ll create country model as following:

app/models/country.ts

export interface Country { id: number, name: string }

Now we’ll create service to return the country data to the component.

<strong>app/services/data.service.ts</strong>

import { Injectable } from '@angular/core'; import { Country } from '../models/country'; const countries: Country[] = [ { id: 1, name: 'Australia' }, { id: 2, name: 'Brazil' }, { id: 3, name: 'Denmark' }, { id: 4, name: 'India' }, { id: 5, name: 'Italy' }, { id: 6, name: 'Japan' }, { id: 7, name: 'Russia' }, { id: 8, name: 'Spain' }, { id: 9, name: 'Turkey' }, { id: 10, name: 'United States' } ]; @Injectable({ providedIn: 'root' }) export class DataService { constructor() { } fetchCountries() { return countries; } }

app.module.ts

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatInputModule } from '@angular/material/input'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, MatAutocompleteModule, MatInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

We’ll need to import MatAutocompleteModule and MatInputModule for material autocomplete component.

app.component.ts

import { Component, OnInit } from '@angular/core'; import { Country } from "./models/country"; import { DataService } from "./services/data.service"; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { countryList: Country[] = []; filteredCountries: Observable<Country[]>; form: FormGroup; constructor(private formBuilder: FormBuilder, private dataService: DataService) { } ngOnInit() { this.countryList = this.dataService.fetchCountries(); this.form = this.formBuilder.group({ country: [] }); this.filteredCountries = this.form.get('country').valueChanges.pipe( startWith(''), map(value => typeof value === 'string' ? value : value.name), map(name => name ? this._filter(name) : this.countryList.slice()) ); } private _filter(value: string): Country[] { const filterValue = value.toLowerCase(); return this.countryList.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0); } displayFn(country: Country): string { return country && country.name ? country.name : ''; } }

Our component creates a form to hold selected country and filter method to filter out the country data while searching in autocomplete

app.component.html

<h1>Angular Material AutoComplete Example</h1> <form class="example-form" [formgroup]="form"> <mat-form-field class="example-full-width"> <mat-label>Select Country</mat-label> <input type="text" matinput="" formcontrolname="country" [matautocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" [displaywith]="displayFn"> <mat-option *ngfor="let country of filteredCountries | async" [value]="country"> {{country.name}} </mat-option> </mat-autocomplete> </mat-form-field> </form> Selected Country: {{form.value | json}}

app.component.css

:host{ display: flex; justify-content: center; align-items: center; height: 100%; width:100%; flex-direction: column; }

Output

Angular material autocomplete search demo

That’s it for angular material autocomplete seach.

I hope you like this article.

Also Read: