【发布时间】:2021-02-01 02:13:40
【问题描述】:
我使用链接到 Angular 8 输入的材料自动完成表单
我是 Angular 的新手,我还在学习。 我已经尝试了一些在 stackoverflow 上找到的解决方案但没有成功(例如:Material autocomplete not displaying list on click)
这是我的 HTML 页面:
<mat-form-field>
<input
matInput
type="text"
placeholder="Equipment"
aria-label="Number"
[formControl]="machineControl"
[formControl]="machineFilter"
[matAutocomplete]="auto"
#machineinput
/>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
这是我的 Typescript 页面:
export class DocumentsListComponent implements OnInit {
machineControl = new FormControl();
options: string[] = [];
filteredOptions: Observable<string[]>;
@ViewChild('machineControl', { static: true }) input: ElementRef;
constructor(public restApi: DocumentsService) {}
ngOnInit() {
this.restApi.getList().then(res => {
[...]
for (const docs of this.Document) {
if (this.options.some(machine => machine === docs.machine)) {
} else {
this.options.push(docs.machine);
}
}
});
this.filteredOptions = this.machineControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option =>
option.toLowerCase().includes(filterValue));
}
我希望自动完成表单会在输入点击时显示,但我需要输入至少 1 个字符才能显示(删除此字符仍会显示自动完成表单)
【问题讨论】:
-
这里的例子都不适合你:material.angular.io/components/autocomplete/examples ?
-
@AkberIqbal 我没有看到此页面上的“过滤器自动完成”示例中缺少的内容。
-
如果你有硬编码的值而不是从你的 rest api 调用,这是否有效?
-
@AkberIqbal 确实有效!如果你知道它为什么会有这样的反应,至少我有一个新的线索要挖掘。编辑:在我输入 1 个字符之前,它似乎没有加载我的选项列表。如果我输入硬编码值,它会起作用,当我输入 1 个字符时,它会显示我来自 API 的值。
-
你应该可以得到帮助...基本上,下拉列表
this.filteredOptions需要在其余api服务调用返回结果后分配