给出 Angular 文档中的示例你可以在这里看到 https://material.angular.io/components/autocomplete/overview#setting-separate-control-and-display-values下面也重复了,我如何访问中的其余对象数据options
?
例如,如果对象不仅仅是键:值格式的简单名称列表,而是更复杂的东西,例如来自 API 的数据:
dataObject = {
name: 'someName',
nameID: 'someId',
foo: 'bar'
}
文档中的示例太简单,没有告诉我如何获取name
显示在输入字段中,同时也获取对应的nameId
在 ts 文件中需要通过 API 返回 PUT 请求。
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
组件.ts:
export class AutocompleteDisplayExample implements OnInit {
myControl = new FormControl();
options: User[] = [
{name: 'Mary'},
{name: 'Shelley'},
{name: 'Igor'}
];
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith<string | User>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this._filter(name) : this.options.slice())
);
}
displayFn(user?: User): string | undefined {
return user ? user.name : undefined;
}
private _filter(name: string): User[] {
const filterValue = name.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}
}