当用户触摸输入字段时,应该显示下拉值,但是只有在我在输入中输入内容后,我的下拉菜单才会出现。
这是我的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;
}
答案 0 :(得分:1)
发生这种情况是因为getAllVacancyDetails()是异步的,并且当您使用startWith(null)发出null时- this.jobs 尚未从后端收到作业列表。因此,作业加载后,您需要通知this.filteredJobs流。您可以这样修改它:
1。在打字稿文件中添加一个新属性:
private _loadedJobs$ = new Subject()
this.jobs = res.body;
之后)添加字符串this._loadedJobs$.next('');
像这样修改您的 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