首页 > 解决方案 > 用户在文本框 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>

标签: htmlangulartypescriptwebdom

解决方案


下拉菜单将根据您输入的文本进行过滤。因此,在给定的示例中,由于您已将 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”,它将仅列出所需的一项。(这是预期的行为


推荐阅读