0

当用户触摸输入字段时,应该会出现下拉值,但我的下拉菜单仅在我在输入中键入内容后才会出现。

这是我的 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;
  }
4

1 回答 1

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

于 2019-11-22T09:19:42.007 回答