我正在尝试在视图中刷新一个数据列表,等待用户在文本框中完成输入并更新结果。尝试使用angular指令,尝试使用Observable和各种超时和debounces,但都不成功。我没办法了。
在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;
}
问题是在检索数据和填充列表后,datalist没有更新。在它存在的方法后,列表又是空的,因此没有数据显示。
我已经添加了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(这是必要的功能)。
如果你稍微改变测试输入为.NET,你就可以清楚地看到这种行为。
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",它将只列出所需的一条。(哪种是预期行为)
您的 formControl
(不知道为什么叫'其他')有一个叫 event
排放出来的 Observable
在每次改变时。您可以 subscribe
到该事件,并使用RxJS操作符 debounceTime()
来指定它应该等待用户停止输入多少毫秒,直到事件发出。
我已经创建了一个简单的 演示,也许更容易理解。
运气好!