angular - Angular Material Autocomplete 以显示来自 RestApi 的员工姓名
问题描述
我希望使用 Angular Material Autocomplete 仅显示来自 Rest API 的员工姓名,该 API 返回数据数组,如下所示:
{
"employees": [
{
"employeeID":"5657",
"employeeName":"James Carter",
"employeeDept": ["Dept1", "Dept2", "Dept3"]
},
{
"employeeID":"5868",
"employeeName":"Helen Burt",
"employeeDept": ["Dept5", "Dept2", "Dept6"]
}
]
}
定义模型如下:
interface Employee {
employeeID: number
empoyeeName: string
employeeDept: string[]
}
我正在使用以下订阅方法来获取数据
this.getAPI.getEmployees()
.pipe(pluck('employees'))
.subscribe(e => {
this.employees = e;
});
下面是过滤的代码:
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
private _filter(value: string): EmployeesList[] {
const filterValue = value.toLowerCase();
return this.employees.filter(option => option.employeeName.toLowerCase().indexOf(filterValue) === 0);
}
但在输入搜索(自动完成)中似乎没有任何工作。请指教。
解决方案
通过写入输入词将过滤器发送到服务器进行过滤。
this.myControl.valueChanges.pipe(
startWith(""),
debounceTime(300),
filter((f) => typeof f == typeof ""),
tap(() => (this.isLoading= true)),
switchMap((value) =>
this.getAPI.getEmployees({
filter:value
}).pipe(finalize(() => (this.isLoading= false)))
)
)
.subscribe((result) => {
this.employees = result;
});
显示自动编译如下
<mat-form-field class="full-width" (click)="clickBox()">
<mat-label>Employee</mat-label>
<input matInput [matAutocomplete]="auto" [formControl]="myControl">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngIf="isLoading" class="is-loading">
<mat-spinner diameter="50"></mat-spinner>
</mat-option>
<ng-container *ngIf="!isLoading">
<mat-option *ngFor="let employee of employees" [value]="employee">
<span>{{ employee.employeeName }}</span>
</mat-option>
</ng-container>
</mat-autocomplete>
选择后我们使用 displayFn 在选择输入中显示员工姓名
displayFn(employee: Employee) {
if (employee) {
return employee.employeeName;
}
}
推荐阅读
- proxysql - 通过套接字连接到 ProxySQL - “没有这样的文件或目录”
- jquery - 在悬停时更改下拉选定选项的颜色
- sql - 在 SQL Server 中为复合主键定义外键
- flutter - 解释应用程序中某个按钮的作用的文本标签
- quanteda - POS 的 textstat_keyness,而不是单词
- datagrid - 如何在 Apache Royale 上使用 js:DataGrid?Language.synthType 的问题
- sql - SQL 查询查找具有多个值的结果
- c# - 增加 system.diagnostics 数据包日志记录大小
- python - 想要在 matplotlib 图例上绘制不同大小/颜色的椭圆
- java - 单击按钮以在新活动中更改颜色-android studio