Autocomplete feature shows usernames while storing corresponding user IDs

I am looking to enhance the autocomplete functionality in my application while also ensuring that the selected user ID is stored in the database.

Specifically, I want the autocomplete feature to display user names for selection purposes, but instead of returning the name, I aim to retrieve and save the corresponding user ID.

After analyzing my code, I believe the issue lies within the following line:

this.userService.getUsers().subscribe(
      (val: any[]) =>{
        this.allFruits = val.map(user => user.username);
        this.fruitCtrl.setValue(null); 
      } 
    )

Link to My Code on Stackblitz

Stackblitz

Component Section

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 Section

<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>

Answer №1

It is important to ensure that the stream of objects, not strings, is present in this.filteredFruits. Relying on ids of selected strings in the current code can be risky, as using the wrong id may lead to bugs.

this.allFruits = val;

To implement this, modify the this._filter function to filter an array of objects rather than an array of strings:

private _filter(value: string): any[] {
  const filterValue = value.toLowerCase();

  return this.allFruits.filter(fruit => fruit.name.toLowerCase().indexOf(filterValue) === 0);
}

Update the Mat Option accordingly:

<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit.id">    
  {{fruit.name}}
</mat-option>

Now, the fruitCtrl should contain the id as its value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

I am having trouble getting the guide for setting up a NextJS app with Typescript to function properly

For some time now, I have been experimenting with integrating Typescript into my NextJS projects. Initially, I believed that getting started with Typescript would be the most challenging part, but it turns out that installing it is proving to be even more ...

Functions designed to facilitate communication between systems

There is an interface that is heavily used in the project and there is some recurring logic within it. I feel like the current solution is not efficient and I am looking for a way to encapsulate this logic. Current code: interface Person { status: Sta ...

Module '@tanstack/react-table' cannot be located even though it has been successfully installed

Currently, I am tackling a TypeScript React project and encountering an issue while attempting to import ColumnDef from @tanstack/react-table in my columns.tsx file. import { ColumnDef } from "@tanstack/react-table"; export type Payment = { id ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

The CORS policy has blocked the Vimeo URL from its origin, stating that the PATCH method is not permitted according to the Access-Control-Allow-Methods preflight response

Using Angular for web development. When uploading a video to Vimeo, it involves 3 steps: Create the video. Upload the video file. Verify the upload. The process of creating a video is successful, however, encountering an error during the vid ...

Unable to locate the name 'X' despite importing the name directly above

I'm a little confused about the situation at hand. The name is clearly mentioned right above. https://i.sstatic.net/D0CEV.png Displayed below is the content of storage-backend.interface.ts: export declare interface StorageBackend extends Storage { ...

Issue with TranslateModule Configuration malfunctioning

I have put together a file specifically for managing ngx-translate configuration: import { Http } from '@angular/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { TranslateLoader, TranslateModu ...

Exploring the relationships between nested tuple types

When exploring the concept of mapped tuple types in TypeScript, the documentation provides an example: type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> }; type Coordinate = [number, number] type PromiseCoordinate = MapToPromise<Coor ...

Is TypeScript to blame for the unexpected token error in Nock?

My code snippet in the ts file looks like this: nock('https://example.test').post('/submit').reply(200,{ "status": "Invalid", "message": "Invalid Request", }); However, when I try to ...

Experiencing a compilation issue while attempting to apply the class-transformer

Encountering an issue while working with a basic example that involves class-transformer. error TS1240: Unable to resolve signature of property decorator when called as an expression. Argument of type 'ClassFieldDecoratorContext<Root, Project[]> ...

What could be causing the Material AngularJS (CSS) on my website to not function properly, unlike the demo that was

I am completely new to AngularJS and I want to incorporate the material design version of AngularJS for developing a form. I followed the beginner's guide and attempted to create something, but it didn't turn out like the one on the website. So, ...

Angular applications can redirect to their own internal pages when linking to an external URL

I've recently started using Angular and have encountered a minor issue. My routing setup is working as expected in the navbar, but I have a link that points to an external URL. When I click on it, instead of redirecting me to the external site, it ta ...

The process of inserting data into MongoDB using Mongoose with TypeScript

Recently, I encountered an issue while trying to insert data into a MongoDB database using a TypeScript code for a CRUD API. The problem arises when using the mongoose package specifically designed for MongoDB integration. import Transaction from 'mon ...

Choose one of the options provided by the radio button that best fits the question using Playwright

Can Playwright docs be used to select a radio button answer based on the question and answer? I need to answer a series of yes/no questions. Here's the HTML structure of the survey site: <!DOCTYPE html> <html lang="en"> <bod ...

When checking for a `null` value, the JSON property of Enum type does not respond in

Within my Angular application, I have a straightforward enum known as AlertType. One of the properties in an API response object is of this enum type. Here is an example: export class ScanAlertModel { public alertId: string; public alertType: Aler ...

Make the text in the SCSS file placeholder bold

Within my Angular front end application, there is a form containing a textarea: <mat-form-field class="full-width"> <textarea class="left-aligned" formcontrolname="x1" matInput placeholder="some text"/> </mat-form-field> In the co ...