Using Material Auto Complete

npm install --save @angular/material @angular/cdk @angular/animation
...
  imports: [
    BrowserModule,
    AppRoutingModule,

    BrowserAnimationsModule,
    MatAutocompleteModule,
    MatInputModule,
    FormsModule,
    ReactiveFormsModule
  ],
...

In src/styles.css, add a prebuilt material theme

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

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;
}

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<State[]>;

  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);
  }
}
<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 autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.value">
        {{option.display}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

  • ng/using_material_auto_complete.txt
  • Last modified: 2019/05/06 16:13
  • by chongtin