I am trying to implement autocomplete, however I want to save the selected user ID in the database.
That is, in autocomplete I want to appear user name to select, but as a return value I do not want the name, but its ID.
I think my problem is in this line:
this.userService.getUsers().subscribe(
(val: any[]) =>{
this.allFruits = val.map(user => user.username);
this.fruitCtrl.setValue(null);
}
)
My Code --Stackblitz
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);
}
)
}
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);
}
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>
You definitely want to have stream of objects, not strings in this.filteredFruits
. With current code base, you would have to find and id of selected string, which sounds fragile - better don't separate key/value pairs from each other or might face bugs when wrong id is used.
this.allFruits = val;
Then change this._filter
function to filter object[]
not string[]
:
private _filter(value: string): any[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.name.toLowerCase().indexOf(filterValue) === 0);
}
And for Mat Option:
<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit.id">
{{fruit.name}}
</mat-option>
Now fruitCtrl
should have an id as a value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.