Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code.

The first problem is that although the input box looks fine, it does not filter the list based on user input.

The second issue is related to my county object having two properties - countyId and countyName. When a county is selected from the list, it displays the countyId instead of the name, as it is bound to the id. How can I modify it to display the name while still being bound to the id for server communication?

Below is the HTML code snippet:

<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
        <input type="text" placeholder="Select County" name="" matInput [formControl]="countyId" [matAutocomplete]="auto">
        
        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
            <mat-option *ngFor="let county of counties" [value]="county.countyId">
                {{county.name}}
            </mat-option>
        </mat-autocomplete>
        
    </mat-form-field>
    

And here is the corresponding TypeScript file code:

window.matchMedia('<br />');
  newCustomerForm: FormGroup;
  counties; // List of counties
  subCounties; 
  filteredCounties: Observable<string[]>;
  
this.newCustomerForm = this._formBuilder.group({
            nationalId: ['', Validators.required],
            name: ['', Validators.required],
            gender: ['', Validators.required],
            phone1: [''],
            phone2: [''],
            countyId: ['', Validators.required],
            subCountyId: ['', Validators.required],
            bishopName: ['', Validators.required],
            bishopPhone: ['', Validators.required],
            address: ['', Validators.required],
            additionalInfo: [''],
            input1: [''],
            input2: [''],
            defaultingRecord: [''],
          });
  
ngOnInit() {
      // Retrieving the list of counties
      this.countyService.getCounties().subscribe((response) => {
        this.counties = response;
        this.filteredCounties = this.newCustomerForm.valueChanges.pipe(
          startWith(''),
          map(value => this._filter(value))
        );
      });
      // Retrieving the list of sub-counties
      this.subCountyService.getSubCounties().subscribe((response) => {
        this.subCounties = response;
      });
    }
    private _filter(value: string): string[] {
      const filterValue = value.toLowerCase();
  
      return this.counties.filter(county=> county.name.toLowerCase().indexOf(filterValue) === 0);
    }
    

Additional context provided through an image: https://i.sstatic.net/wi0v5.jpg

Answer №1

It is recommended to use your object in the template instead of single properties:

<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
    <input type="text" placeholder="select county" name="country" matInput [formControl]="country" [matAutocomplete]="auto">

    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let countryof countries" [value]="country">
            {{country.name}}
        </mat-option>
    </mat-autocomplete>

</mat-form-field>

Add a component function displayFn() as shown below:

displayFn(country?: Country): string | undefined {
    return country? country.name : undefined;
  }

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

React error: Unexpected token < in JSON when fetching local file

I've encountered an issue with my React app. I have a JSON file in the public directory that I was successfully fetching data from in my main App.js file without any errors. However, after running `npm run build`, I started getting the error message: ...

Guide to embedding an iframe generated with JavaScript into a React component

I'm currently working on developing an app that will utilize an iframe. The goal is to have controllers in place to adjust the style of the iframe and add text to it, essentially creating a preview function. I've been attempting to use Javascript ...

Accessibility issues detected in Bootstrap toggle buttons

I've been experimenting with implementing the Bootstrap toggle button, but I'm having an issue where I can't 'tab' to them using the keyboard due to something in their js script. Interestingly, when I remove the js script, I'm ...

What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data: var data = [ { "name": "wiredep", "version": "4.0.0", "link": "https://github.com/taptapship/wiredep", "lice ...

Issue encountered while building Angular 4 application for production due to CSS-loader error

Whenever I attempt to build my application using 'ng build', it works fine. However, when I try to run 'ng build --prod --aot=false' to build it for production, I encounter a perplexing error message: devrep@dev-laptop:~/Document ...

What is the best way to incorporate a button that, when clicked, reveals two separate images on the frontend?

describe food option heredescribe juice option hereHow can I create a button using HTML, CSS, JavaScript, and Bootstrap that displays different images for food and juices when clicked? For example, clicking on "food" will display 3 different food images, w ...

Using array.map() in React does not display elements side by side within a grid container

I'm currently working with React and material-ui in order to achieve my goal of displaying a grid container that is populated by an array from an external JavaScript file. The challenge I am facing is getting the grid to show 3 items per row, as it is ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

What is the reason behind jQuery's .html("abc") only providing temporary insertion?

I have come across an issue with an HTML button that triggers a function. Whenever the button is clicked, a div is inserted but it only appears for a brief moment before disappearing both visually and in the HTML tree. function openBox () { $( '#0&a ...

Encountering a JSON error in Ionic 3 due to a circular structure conversion

Hello everyone, I am a beginner in Angular 2+ and Ionic 3. I am currently attempting to submit a login form from my Ionic 3 app to my ASP.NET Web API application for token-based authentication. However, I keep encountering the following error: converting c ...

The collapse component in ReactJS does not accept props values for the href attribute

When I click the button inside of Collapse.js, the Card component should be displayed. However, it is not receiving 'props.href1' as an href attribute and is showing an error: Line 11:20: Parsing error: Unexpected token, expected "..." 11 | href ...

Performing an AngularJS $http POST request with a combination of JSON parameter and query string

I'm currently trying to write an AJAX call using Angular's $http object in order to send a post request with JSON in the body and a query string appended to the URL. Despite going through the documentation for $http, looking for solutions on SO, ...

The npm system is encountering difficulties in parsing the package.json file

Having recently started using npm and node, I decided to create a react app with truffle unbox react using npm init react-app. Despite attempting to reinstall npm and clear the cache multiple times, I consistently encounter an error when trying to run sudo ...

Ways to determine whether a DOM textnode is a hyperlink

Is there a more foolproof method for determining if a DOM textnode represents a hyperlink? The code snippet below currently only checks if the node is directly enclosed in an anchor tag, which may not be sufficient if the <a> element is higher up i ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

Angular BotDetect encountering CORS issue when connecting to ASP.NET WebApi2 backend

I'm currently utilizing Botdetect in an angular 8 project with an ASPNET WebApi2 Backend. However, I encountered the following error: Access to XMLHttpRequest at 'http://localhost:29739/simple-captcha-endpoint.ashx?get=html&c=yourFirstCap ...

Using Angular-Meteor to make an HTTP request

I'm attempting to utilize the HTTP.call method with angular-meteor. Within my API backend folder, I am trying the following within a method: this.unblock(); try { const result = HTTP.call('GET', 'https://api.foursquare.com/v2/users/ ...

What are the benefits of initializing my Angular2 reactive form in the constructor instead of ngOnInit?

According to several responses, it is recommended to initiate the initial functions of an Angular2 application within the ngOnInit() method, reserving the constructor specifically for dependency injection tasks. However, the Reactive Forms tutorial I am c ...

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...