Angular Material Autocomplete Tutorial | Angular 8 Autocomplete

Themomsco [CPS] IN

Angular material provides a nice built-in feature to enhance an input field into suggested options and it is done by Angular material autocomplete module.

In this tutorial, we will learn how to use Angular autocomplete features in a project.

Prerequisite

  1. Angular CLI
  2. NodeJs
  3. Git

Let’s start by creating a new project ‘angular-material-autocomplete’ using Angular CLI.

Create New Angular Project

To create a project, open command prompt or terminal and type the following command.

ng new angular-material-autocomplete

This command will create a new project, now open this project in the code editor. (For me I am using VS Code)

To open the project in Vs Code editor use command code .

also, open the project in the browser using command ng serve. (see the screenshot below)

open-angular-project

 

 

We have now a running angular project on our machine when you browse http://localhost:4200/

Install Angular Material

To use the Angular material autocomplete feature we need to install the Angular Material package into our project.

So run the following command to install Angular Material.

ng add @angular/material

Import Angular Material

After a successful installation of Angular Material, we will import the Angular material autocomplete module in our module file.

Open the app.module.ts file and import autocomplete module dependency.

Your code should look like the same as given below:

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { 
  MatAutocompleteModule,
  MatFormFieldModule,
  MatInputModule
} from '@angular/material';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,

   MatAutocompleteModule,
   MatFormFieldModule,
   MatInputModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Finally, we are ready to include the autocomplete feature in our project.

Open app.component.ts file and add some code to test the functionality. The file content should look like the below code.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

public skills: string[] = ["Angular", "React", "Node", "Java"]; // skills

constructor() {}

}

In the above code, we have a property called skills which is an array of user’s skill. We will use *ngFor directive to loop through on skills properties and display user’s skill as an autocomplete.

Open app.component.html file and insert the following code:

<form>
    <mat-form-field>
        <input type="text" matInput placeholder="Skills" [matAutocomplete]="auto" />
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let skill of skill" [value]="option">{{ skill }}</mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

In the above code we have used [matAutocomplete] directive which reference to #auto=”matAutocomplete”. It triggers the autocomplete module when we mouse click on the input field.

Angular Material Autocomplete Object Value

Open the app.component.ts and app.component.html file and replace the value by given code below.

Change skills property value in app.component.ts file

public skills = [
    {name: "Angular"},
    {name: "Java"},
    {name: "React"},
    {name: "Node"},
    {name: "Vue"}
];

Replace the code in app.component.html file

<form class="form">
    <mat-form-field>
        <input type="text" matInput placeholder="Skills" [matAutocomplete]="auto" />
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let skill of skills" [value]="skill">{{ skill.name }}</mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

<router-outlet></router-outlet>

Now test it on the browser, When you see the dropdown, It will look like the same as it should be. But, when you choose the option the value will not get selected and input value shows [object Object].

Use displayWith to Show Object Value

Using displayWith directive we will fix the issue:

Add [displayWith]=”displayFn” on line no – 4 like this:

<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">

Now, got to app.component.ts file and create a new function called displayFn which will be bind with [displayWith] directive.

displayFn(subject) {
    return subject ? subject.name : undefined;
}

that’s it.

So, when you select any option the [displayWith] directive triggers the displayFn function which takes the object as an argument and returns the string based on the selected value.

Conclusion

If you want to integrate material Autocomplete functionality in Angular 6|7|8, this tutorial will work with every version.

Finally. Angular Material Autocomplete tutorial is over. Feel free to ask questions related to this tutorial in the comment section below.

 

 

Leave a Reply