步骤 | 描述 |
1 | 创建一个名为 materialApp 的项目,如 Angular 6-项目设置 章节所述。 |
2 | 修改app.module.ts、app.component.ts、app.component.css和app.component。 html 如下所述。保持其余文件不变。 |
3 | 编译并运行应用程序以验证实现逻辑的结果。 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatAutocompleteModule,MatInputModule} from '@angular/material'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MatAutocompleteModule, MatInputModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
<form class = "tp-form"> <mat-form-field class = "tp-full-width"> <input type = "text" placeholder = "US State" aria-label = "Number" matInput [formControl] = "myControl" [matAutocomplete] = "auto"> <mat-autocomplete #auto = "matAutocomplete"> <mat-option *ngfor = "let state of states" [value] = "state.value"> {{state.display}} </mat-option> </mat-autocomplete> </mat-form-field> </form>
.tp-form { min-width: 150px; max-width: 500px; width: 100%; } .tp-full-width { width: 100%; }
import { Component } from '@angular/core'; import { FormControl } from "@angular/forms"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'materialApp'; myControl = new FormControl(); states; constructor(){ this.loadStates(); } //build list of states as map of key-value pairs loadStates() { var 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 }; }); } }