在Angular中,可以通过在输入时自动显示建议列表来改善用户体验。以下是如何实现这一功能的示例代码。
HTML代码:
- {{ suggestion }}
TypeScript代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
searchText: string;
suggestionList: string[];
constructor() {
this.searchText = '';
this.suggestionList = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
}
onSearch(): void {
this.suggestionList = ['apple', 'banana', 'cherry', 'date', 'elderberry'].filter(item =>
item.toLowerCase().includes(this.searchText.toLowerCase())
);
}
selectSuggestion(suggestion: string): void {
this.searchText = suggestion;
this.suggestionList = [];
}
}
该示例代码将在输入框上监听键盘事件,并在每次键入时更新建议列表。它在建议列表中使用ngFor指令遍历搜索结果,并在点击任何建议后将选定建议输入框中的文本。