【问题标题】:Auto complete filter function only works after type something自动完成过滤功能仅在输入内容后才有效
【发布时间】:2020-03-17 00:56:44
【问题描述】:

下拉值应该在用户触摸输入字段时出现,但我的下拉值只有在我输入内容后才会出现。

这是我的 HTML 代码:

<mat-form-field class="example-chip-list" style="width:100%">
    <input placeholder="Vacancy" formControlName="job" [matAutocomplete]="auto" matInput>
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let job of filteredJobs | async" [value]="job">
        {{job?.refId}} - {{job?.title}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>

这是我的类型脚本函数:

ngOnInit() {
   this.getAllVacancyDetails();

    this.filteredJobs = this.vacancyForm.controls['job'].valueChanges.pipe(
      startWith(null),
      map((possition: string | null) => possition ? this._filterJobs(possition) : this.jobs)
    );
  }


public getAllVacancyDetails() {
    this.vacancyService.getAllvacancies().subscribe(
      res => {
        if (res.status == 200) {
          this.jobs = res.body;
        }
      },
      err => {
        this.openSnackbar("An Error Occured while Loading Dropdown Data");
      }
    );
  }

     private _filterJobs(value: any): Job[] {
        let jobsList: Job[] = new Array();
        if (!(value instanceof Object)) {

          const filterValue = value.toLowerCase();
          this.jobs.forEach(job => {
            if (job.title.toLowerCase().indexOf(filterValue) === 0) {
              jobsList.push(job);
            }
          });
          if(jobsList.length == 0){
            this.vacancyForm.controls['job'].setErrors({'incorrect': true});
          }
        }


    return jobsList;
  }

【问题讨论】:

    标签: html typescript filter angular6 mat-autocomplete


    【解决方案1】:

    发生这种情况是因为 getAllVacancyDetails() 是异步的,并且当您使用 startWith(null) 发出 null 时 - this.jobs 尚未从后端收到作业列表。因此,一旦加载作业,您需要通知 this.filteredJobs 流。你可以像这样修复它:

    1.在打字稿文件中添加一个新属性:

    private _loadedJobs$ = new Subject()
    
    1. getAllVacancyDetails() 方法中(就在this.jobs = res.body; 之后)添加一个字符串this._loadedJobs$.next('');
    2. 像这样修改您的 this.filteredJobs 流:

      this.filteredJobs = merge(this.vacancyForm.controls['job'].valueChanges, this._loadedJobs$.next('')).pipe( ...和你现在一样)

    我很确定有更优雅的方法来修复或重做它,但我只是想给你一些提示 :) 希望它会有所帮助。还有例子:

    https://stackblitz.com/edit/angular6-material-autocomplete-qrlhaf?file=src/app/app.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 2016-07-15
      • 1970-01-01
      相关资源
      最近更新 更多