I am currently working with an autocomplete component. I am passing an array of objects and would like to retrieve all item information (option) when an option is selected, not just the field value (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>
Component 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));
}
}
Currently utilizing (optionSelected)
, but it only provides the selected value. I also need to obtain the id.
This customization will enhance the functionality of my autocomplete feature.