给定Angular文档you can see here中的示例并在下面重复,如何访问options
中的其余对象数据?
例如,如果该对象不仅仅是一个简单的key:value格式的名称列表,而是更复杂的东西,例如来自API的数据:
dataObject = {
name: 'someName',
nameID: 'someId',
foo: 'bar'
}
文档中的示例太简单了,没有告诉我如何获取name
才能在输入字段中显示,以及如何在ts文件中获取相应的nameId
通过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>
component.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);
}
}
答案 0 :(得分:1)
我认为您正在寻找onSelectionChange选项:
您可以简单地添加到mat-option中:
(onSelectionChange)="setID(option.nameID)"
每次选择一个值时,都会触发该事件。