显示选项列表的自动完成选择。每个选项都是一个对象。我想显示每个选项的名称,但发送它的 ID。这段代码有效。但是一旦选择了该选项,输入就会显示 id。我想显示名字。
文档建议使用 [displayWith]="displayFn" 但它需要将 [value]="freespin.id" 更改为 [value]="freespin" 而我不希望这样。
我还没有找到解决办法。
<mat-form-field>
<mat-label>Freespin</mat-label>
<input type="text"
placeholder="Select a freespin"
matInput
formControlName="freespin"
[matAutocomplete]="auto">
<mat-autocomplete requireSelection #auto="matAutocomplete">
<mat-option *ngFor="let freespin of filteredFreespins[i] | async" [value]="freespin.id">
{{freespin.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
您可以尝试使用
displayWith
属性吗?请在下面找到一个工作示例!
html
<form class="example-form">
<input
type="text"
placeholder="Search for a street"
[formControl]="control"
[matAutocomplete]="auto"
class="example-input"
/>
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayWith.bind(this)"
>
@for (street of filteredStreets | async; track street) {
<mat-option [value]="street.id">{{street.name}}</mat-option>
}
</mat-autocomplete>
</form>
ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
import { AsyncPipe } from '@angular/common';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
/**
* @title Plain input autocomplete
*/
@Component({
selector: 'autocomplete-plain-input-example',
templateUrl: 'autocomplete-plain-input-example.html',
styleUrls: ['autocomplete-plain-input-example.css'],
standalone: true,
imports: [FormsModule, MatAutocompleteModule, ReactiveFormsModule, AsyncPipe],
})
export class AutocompletePlainInputExample implements OnInit {
control = new FormControl('');
streets: any[] = [
{ id: 1, name: 'Champs-Élysées' },
{ id: 2, name: 'Lombard Street' },
{ id: 3, name: 'Abbey Road' },
{ id: 4, name: 'Fifth Avenue' },
];
filteredStreets: Observable<any[]>;
ngOnInit() {
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.name).includes(filterValue)
);
}
displayWith(val: any) {
if (val) {
const found = this.streets.find((x: any) => x.id === val);
return found && found.name ? found.name : val;
} else {
return val;
}
}
private _normalizeValue(value: string): string {
return value.toLowerCase().replace(/\s/g, '');
}
}