首页 > 解决方案 > Angular 7 Material 自动完成选项未显示

问题描述

我使用的是angular page中的确切代码,唯一的区别是我使用的是 Angular 7 和 @angular/material 7。

组件.html:

<!-- added to see that value is changing -->
<li *ngFor="let street of filteredStreets | async">{{street }}</li> 

<form class="example-form">
    <input type="text"
           matInput
           placeholder="Search for a street"
           [formControl]="control"
           [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let street of filteredStreets | async" [value]="street">
            {{street}}
        </mat-option>
    </mat-autocomplete>
</form>

组件.ts:

control = new FormControl();
streets: string[] = ['Champs-Élysées', 'Lombard Street', 'Abbey Road', 'Fifth Avenue'];
filteredStreets: Observable<string[]>;

constructor() {
    this.filteredStreets = this.control.valueChanges.pipe(
        startWith(''),
        map(value => this._filter(value))
    );
}

private _filter(value: string): string[] {
    const filterValue = this._normalizeValue(value);
    return this.streets.filter(street => this._normalizeValue(street).includes(filterValue));
}

private _normalizeValue(value: string): string {
    return value.toLowerCase().replace(/\s/g, '');
}

开发工具: 在此处输入图像描述

标签: angularangular-materialangular7

解决方案


推荐阅读