I am currently utilizing a Mat-autocomplete feature that allows for loading a list of "users".
Within the autocomplete functionality, I aim to exhibit the username while retaining the selected user ID value.
Originally, I had:
this.allFruits = val.map(user => user.username);
However, I updated it to retrieve all fields, but encountered difficulty in retrieving the chosen user IDs. Can anyone assist me with this?
this.allFruits = val;
Check out my code DEMO
HTML
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList>
<mat-chip
*ngFor="let fruit of fruits"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(fruit)">
{{fruit}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input
placeholder="New fruit..."
#fruitInput
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
{{fruit}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
Component
constructor(private userService: UserService) {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
ngOnInit() {
this.userService.getUsers().subscribe(
(val: any[]) =>{
this.allFruits = val.map(user => user.username);
this.fruitCtrl.setValue(null); //use this to apply changes instantly
}
)
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}