html - 用户在文本框 Angular 7 中输入完成后刷新视图中的数据列表
问题描述
在等待用户完成在文本框中输入并更新结果后,我正在尝试刷新视图中的数据列表。尝试了角度指令,尝试了 Observable 和各种超时和去抖动,但没有运气。我没有选择了。
在 html 文件中:
<input type="text" class="form-control" id="Other"
(keyup)="onKeySearch($event)" list="dynamicList" formControlName="Other"/>
<datalist id="dynamicList">
<option *ngFor="let employee of employeesList" [value]="employee.Name">
{{employee.Name}}</option>
</datalist>
在 .ts 文件中:
public employeesList: EmployeeData[] = [];
timeout: any = null;
getEmployeesList(name : string) {
let empList: EmployeeData[] = [];
// get employees list from service
this.employeeService.getEmployeesList(name).subscribe((data: any) => {
empList = data;
console.log(empList)
})
return empList;
}
public onKeySearch(event: any) {
let empListt: EmployeeData[] = [];
clearTimeout(this.timeout);
var $this = this;
this.timeout = setTimeout(() => {
empListt = $this.getEmployeesList(event.target.value);
console.log(empListt)
}, 1000);
this.employeesList = empListt;
}
问题是数据列表在检索数据并填充列表后没有更新。存在该方法后,列表再次为空,因此没有数据可显示。
我添加了 stackblitz 示例代码,代码与上面类似(行为相同):
.ts 文件:
import { Component, VERSION, OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { distinctUntilChanged, debounceTime, tap } from "rxjs/operators";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
searchControl = new FormControl("");
message = "";
public employeesList: string[] = [];
ngOnInit() {
this.searchControl.valueChanges
.pipe(
tap(() => (this.message = "User is typing...")),
distinctUntilChanged(),
debounceTime(1000)
)
.subscribe(res => {
this.message = "User finished typing!";
this.employeesList.push('1');
this.employeesList.push('2');
this.employeesList.push('3');
});
}
}
.html 文件:
<input [formControl]="searchControl" list="dynamicList">
<datalist id="dynamicList">
<option *ngFor="let employee of employeesList">
{{employee}}</option>
</datalist>
<span> {{message}} </span>
解决方案
下拉菜单将根据您输入的文本进行过滤。因此,在给定的示例中,由于您已将 1,2 和 3 个值推送到列表中,因此下拉列表将仅列出过滤后的值。
例如。如果输入 1,下拉列表将有 1(这是必需的功能)
如果您将测试输入稍微更改为:
ngOnInit() {
this.searchControl.valueChanges
.pipe(
tap(() => (this.message = "User is typing...")),
distinctUntilChanged(),
debounceTime(1000)
)
.subscribe(res => {
this.message = "User finished typing!";
this.employeesList.push('Employee 1');
this.employeesList.push('Employee 2');
this.employeesList.push('Employee 3');
});
}
现在,当您搜索“员工”时,它将列出所有 3 个,如果您搜索“员工 1”,它将仅列出所需的一项。(这是预期的行为)
推荐阅读
- json - 如何在对象具有字符串键的 Golang 中解组 JSON
- docusignapi - DocuSign - OAuth 授权代码授予 - 多个用户 - 获取访问和刷新令牌时出错
- angularjs - 无法使用 AngularJS 将 Json 数据与表头绑定
- facebook-graph-api - 为 Facebook 页面 API 开发
- amazon-sagemaker - 设备上没有剩余空间 [Amazon SageMaker]
- r - 具有预定义质心的 K 均值聚类
- excel - 保存 Outlook 邮件附件
- string - 如何创建一个递归函数,该函数返回单个参数(字符串列表)的副本,但每个字符在每个位置都重复?
- vue.js - Vuejs Vuetify 如何在 v-select 中访问对象的属性
- css - 使用css调整浏览器窗口大小时如何使图像自动调整大小?