====== Using Material Auto Complete ====== ===== Installing the Related Dependencies ===== npm install --save @angular/material @angular/cdk @angular/animation ===== Adding the Module in app.module.ts ===== ... imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatAutocompleteModule, MatInputModule, FormsModule, ReactiveFormsModule ], ... ===== Add the Material css theme to the Project ===== In src/styles.css, add a prebuilt material theme @import "~@angular/material/prebuilt-themes/indigo-pink.css"; ===== Adding My Own Interface ===== The interface call ''state'', and will hold two strings ''display'', and ''value'' ng generate interface state In state.ts: export interface State { value: string; display: string; } ===== Initialize the Auto Complete List in the Component ===== In app.component.ts import {Component, OnInit} from '@angular/core'; import {FormControl} from "@angular/forms"; import {map, startWith} from 'rxjs/operators'; import {Observable} from "rxjs"; import {State} from "./state"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'materialApp'; myControl = new FormControl(); states: State[]; filteredOptions: Observable; ngOnInit(): void { this.loadStates(); this.filteredOptions = this.myControl.valueChanges.pipe( startWith(''), map(value => this._filter(value)) ); } private _filter(value: string): State[] { const filterValue = value.toLowerCase(); return this.states.filter(option => option.value.toLowerCase().indexOf(filterValue) === 0); } //build list of states as map of key-value pairs loadStates() { let allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\ Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\ Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\ Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\ North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\ South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\ Wisconsin, Wyoming'; this.states = allStates.split(/, +/g).map(function (state) { return { value: state.toUpperCase(), display: state }; }); console.log(this.states); } } ===== Setup the view in html =====
{{option.display}}
===== How It Should Look Like ===== {{ :ng:ng_auto_complete.png?nolink&200 |}} ===== Reference ===== * [[https://v5.material.angular.io/components/autocomplete/overview]] * [[https://www.tutorialspoint.com/angular_material7/angular_material7_autocomplete.htm]]