要使用 Angular Material 的自动完成组件,需要按照以下步骤进行设置:
npm install @angular/material @angular/cdk
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatInputModule } from '@angular/material/input';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatAutocompleteModule,
MatInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
{{ option }}
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myControl = new FormControl();
options: string[] = ['Option 1', 'Option 2', 'Option 3'];
filteredOptions: Observable;
constructor() {
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));
}
}
以上代码示例中,options
数组中是自动完成的选项列表。在 _filter
方法中,使用 valueChanges
监听输入框的值变化,并根据输入的值过滤出匹配的选项列表。
这样就完成了 Angular Material 自动完成组件的设置。当用户在输入框中输入内容时,会根据输入的值动态显示匹配的选项。