gpt4 book ai didi

javascript - 选择时的 Angular 自动完成获取所选值的所有对象

转载 作者:行者123 更新时间:2023-12-04 14:09:57 26 4
gpt4 key购买 nike

我有一个自动完成组件。
我传递了一个对象数组。
我希望当我选择一个选项时,我得到所有项目信息( option )而不仅仅是字段值( option.name )

<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)='selectOption($event.option)'>
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<router-outlet></router-outlet>
</form>
组件 ts
export class SearchLeagueComponent implements OnInit {
constructor(private searchLeagueService: SearchLeagueService) { }
myControl = new FormControl();
options: ILeague[] = [
{
_id: '',
teams: [],
name: '',
sport: ''
}
];
filteredOptions: Observable<ILeague[]> | undefined

ngOnInit() {
this.searchLeagueService.getLeaguesList().toPromise().then(data => this.options = data)
this.filteredOptions = this.myControl.valueChanges
.pipe(
//startWith(''),
map((value: string) => this._filter(value))
);
}
selectOption(val: string) {
console.log(val)
}
private _filter(value: string): ILeague[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().includes(filterValue));
}
}
其实我用的是 (optionSelected)但它只返回选定的值。
我也应该得到身份证。

最佳答案

您应该通过 ($事件)选择选项()。


<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)='selectOption($event)'>
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<router-outlet></router-outlet>
</form>

然后像这样在 selectOption() 中获取您的对象
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';


selectOption(e: MatAutocompleteSelectedEvent) {
const item: **YOUR INTERFACE** = e.option.value;
console.log(item);
}
enter image description here

关于javascript - 选择时的 Angular 自动完成获取所选值的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65063456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com