Retrieve all objects of the selected value using Angular autocomplete when an option is selected

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.

Answer №1

You need to pass the ($event) parameter into the selectOption() function.


<form class="example-form">
    <mat-form-field class="example-full-width">
        <input type="text" placeholder="Choose 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>

Then access your object in selectOption() using this method:

import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';


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

https://i.sstatic.net/FilHY.png

Answer №2

Utilize the itemDisplayFn function for displaying options

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

  itemDisplayFn(item: YOUR INTERFACE) {
        return item? item.name: '';
    }

Answer №3

I encountered a similar development issue recently and managed to resolve it using the following methods:

HTML

<mat-autocomplete #auto="matAutocomplete" (optionSelected)='selectOption($event.option,$event.option._element.nativeElement.OptionValue)'>
    <mat-option [OptionValue]="option" *ngFor="let option of filteredOptions | async" [value]="option.name">
        {{option.name}}
    </mat-option>
</mat-autocomplete>

.ts File

selectOption(val: string, option: any) {
  console.log(val);
  console.log("option : ", option);
}

I hope this solution works for you as well.

In this example, I assigned the current option value to a custom attribute (OptionValue). When the event is triggered, this attribute value is passed as an argument to the 'selectOption()' function.

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

Database only accepts numerical data for insertion, rejecting any characters or alphanumeric entries

On a webpage, I have an input field through which I am passing the value into an ajax POST request. After logging everything in my JavaScript file and confirming that all is working as expected. In my PHP file, I retrieve the input value using $message = ...

Retrieve the value from an HTML class using Angular

The Person Object has a field called schoolId, but the School object (not shown here) contains the schoolName. I want to display the schoolName in the table data cell instead of the schoolId from the Person Object. How can I achieve this? <tr *ngFor=& ...

Angular 4's Panel Window: A User-Friendly Interface

Having experience with Adobe Flex, I am familiar with creating new panel windows in Action Script by using the 'new' keyword and popping them up using popups. The customization of these windows was achieved through functions provided in the Panel ...

verifying if checkbox is selected using a while loop in PHP

Help Needed: I am currently trying to loop through some code, but I'm struggling with checking checkboxes using PHP. Could someone please review my code and provide guidance on what needs to be added? Any assistance would be greatly appreciated. Thank ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

React component is being rendered, but it is not mounting properly, so it is unable

In my FillForm functional component, I am calling a list of objects to be rendered sequentially within the FormFiller function. The components are rendering correctly, but I encounter an error when trying to change their internal state. Warning: Can&apos ...

Make sure to validate for null values when extracting data using the useSelector hook

Could someone help me with checking for null while destructuring data? const { vehicles: { data: { reminderVehicles }, }, } = useSelector((state) => state); The code snippet above is throwing an error message: Attempting to ...

Arrange a div close to another div with the help of absolute positioning

My goal is to create a tooltip-like positioning for an element within the same container as another element. When clicked, this particular element will display a div containing a table. You can find the complete code here: http://jsbin.com/xihebol When s ...

Creating a String-only pattern Validator: A step-by-step guide

Below is the code I've written: ***<input type="text" placeholder="First Name" name="firstName1" [(ngModel)]="firstName" #firstName1="ngModel" required pattern="^[a-z0-9_-]{8,15}$" >*** ...

Encountering a permission issue while trying to execute npm install -g @angular/cli command

I recently started using Angular and am working on a new project. However, when I try to execute the following command: npm install -g @angular/cli I encounter the error message below: npm WARN checkPermissions Missing write access to /usr/local/lib/no ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

Receiving error in TypeScript while using the 'required' attribute in the input field: "Cannot assign type 'string | undefined' to parameter expecting type 'string'"

In my TypeScript code, I am currently in the process of transitioning from utilizing useState to useRef for capturing text input values. This change is recommended when no additional manipulation necessitating state or rerenders is required. While I have ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

Ensure history.back() does not trigger Confirm Form Resubmission

Within my web application, every form submission is directed to an action folder. Once the process is complete, the user is redirected back to their original location. However, a problem arises when the user performs an action that requires the application ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

What could be the reason for the modal-side modal-top-right class not functioning properly in Bootstrap modals

Here is the code snippet: <div class="modal fade right" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-side modal-bottom-right"> <div class="modal-content"&g ...

Strange behavior observed when resizing objects in Three.js WebGl

Everything was going smoothly with my code until I decided to enable WebGL. It seems that the function responsible for resizing my object every frame rate stopped working. function animate(){ window.requestAnimationFrame(animate); s.setPositio ...

Top tips for resolving Swiper Js initial loading issues in a Carousel!

After implementing swiper js from , I encountered an issue. The initial loading displays only a single carousel item before the rest start appearing, creating a glitchy effect. To clarify, when the website is loaded, only the first item is visible in the ...

Developing mongoose models using TypeScript for subdocuments

Exploring the integration of mongoose models with typescript, following a guide available at: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models. Unsure how arrays of subdocuments align with this setup. For instance, consider the model ...