Angular中实现自动完成组件的关键在于利用Angular Material中提供的mat-autocomplete组件,并在代码中定义相应的事件。下面是一个示例:
HTML模板代码:
{{option}}
在上面的HTML代码中,我们首先引入mat-form-field和mat-autocomplete两个组件,分别用于输入框和下拉列表的展示。需要注意的是,我们在mat-autocomplete中定义了一个名为“auto”的模板引用变量,并绑定了一个名为“myControl”的FormControl。
接着,我们在Component中编写相关的事件处理代码:
TypeScript代码:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
@Component({
selector: 'app-auto-complete',
templateUrl: './auto-complete.component.html',
styleUrls: ['./auto-complete.component.css']
})
export class AutoCompleteComponent implements OnInit {
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable;
constructor() { }
ngOnInit() {
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));
}
selectValue(event) {
// Do something when a value is selected
console.log(event.option.value);
}
}
在上面的Component代码中,我们首先引入FormControl