Angular Material's autocomplete feature allows users to easily search

I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field.

However, my next task is to enable filtering of the options as the user types. I tried following the Angular Material tutorial but encountered errors along the way.

One recurring error message I receive is:

An argument for 'callbackfn' was not provided.
This issue arises when attempting to implement the filteredOptions functionality.

Furthermore, once I complete this step, the subsequent challenge would be to display the name in the first input field and the corresponding phoneNumber in the adjacent input field. I'm currently seeking suggestions on how best to approach this problem!

IDriverDate interface:

export interface IDriverData {
    name: string;
    phone: string;
}

messages.component.ts:

My driver data is stored within driverData array. Although unclear why I need to use filteredOptions instead of directly manipulating the data.

driverData: IDriverData[];
filteredOptions: Observable<IDriverData[]>;

ngOnInit(): void {
    this.getMessages();

    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(driver => typeof driver === 'string' ? driver : driver.name),
        map(name => name ? this._filter(name) : this.driverData.slice())
      );
   }

displayFn(driver): string {
    return driver ? driver.name : driver;
  }

private _filter(name: string): IDriverData[] {
    const filterValue = name.toLowerCase();

    return this.driverData.filter(driver => driver.name.toLowerCase().indexOf(filterValue) === 0);
  }

messages.component.html:

<div>
    <mat-card>
        <mat-card-title>Verstuur een bericht:</mat-card-title>
        <mat-divider></mat-divider>
        <mat-card-content>
            <div class="input">
                <mat-form-field>
                    <input matInput placeholder="Naam" [(ngModel)]="name" [formControl]="myControl" [matAutocomplete]="auto">
                    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
                        <mat-option *ngFor="let driver of driverData" [value]="driver">
                            {{driver.name}}
                        </mat-option>
                    </mat-autocomplete>
                </mat-form-field>

                <mat-form-field>
                    <input matInput placeholder="Telefoonnummer" type="tel" [(ngModel)]="number">
                </mat-form-field>
            </div>
            <mat-divider class="subdivider"></mat-divider>
            <div class="message">
                <mat-form-field>
                    <textarea id="message" matInput placeholder="Bericht: " rows=10 [(ngModel)]="content"></textarea>
                </mat-form-field>
            </div>
        </mat-card-content>
        <mat-card-actions>
            <button mat-raised-button (click)="sendMessages()">Verstuur</button>
        </mat-card-actions>
    </mat-card>
</div>

Answer №1

To update your mat-option element functionality, you should now iterate through the Observable filteredOptions array using the async pipe, instead of iterating through the entire driverData array:

<mat-option *ngFor="let driver of filteredOptions | async" [value]="driver">

When capturing and populating your selection, consider using the optionSelected event to pull values from your FormControl into a variable like this.number. Avoid using [(ngModel)]="name" on the input as it already has a FormControl. Inputs should only use ngModel or FormControls, not both.

(optionSelected)="driverSelected()"

In the driverSelected method, do the following:

public driverSelected(): void {
    const driver = this.mycontrol.value;
    this.number = driver.number;
}

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

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

Ways to return bsDateRangePicker to its default value

I'm currently working on creating reactive forms using Angular 9 and integrating ngx-bootstrap. One issue I am facing is with the daterangepicker functionality. Whenever I utilize the form.reset() function, it clears the input field entirely instead o ...

Modify/remove table using a popup window

My goal was to include edit and delete buttons within a table. When these buttons are clicked, a popup window opens allowing us to modify the values and then update them in the table using Angular. ...

The browser is not displaying the HTML correctly for the Polymer Paper-Menu component

I attempted to implement a paper-menu, but I am facing issues with the rendered HTML and its interaction. When I click on a menu item, the entire list disappears due to the paper-item elements not being properly placed inside a key div within the paper-men ...

Having trouble establishing a default value for Material Multiselect in Angular 6

I am currently attempting to incorporate a multiselect feature in an Angular application using Material design. However, I am encountering an issue where the default selected types are not working as expected when the page is opened in Edit mode. Displaye ...

Using dynamic variables from a service to override Bootstrap variables in Angular

It seems like I've hit a dead end. My goal is to override the bootstrap SCSS $primary variable with my own, which I want to load into a component through a service from an external JSON config file (the content of this file can vary). The solution th ...

Discover the art of customizing chart series color

How do I change the color of a series in a chart? I am trying to customize the color of a specific item on my pie chart. <kendo-chart-series-item type="pie" [data]="source" field="value" [color]="color ...

My goal is to create a carousel using Vue 3 with the Composition API and TypeScript

Creating a carousel with Vue 3 and TypeScript has been quite challenging for me. I heard about using "vue-awesome-swiper" to build a carousel, but I couldn't find a tutorial on how to use it. Does anyone know how to utilize this tool effectively? Alte ...

Creating a dynamic form in Angular using reactive forms and form builder that pulls real-time data from the server

I have been struggling for the past two days to organize the data in the correct order but so far, I haven't been successful. Essentially, I retrieve some data from the server and present it to the client along with additional fields that the client n ...

Issue with refreshing route in Node.js: Unable to access /

When serving my Angular 7 project on a Node.js server, I encountered an issue where upon page refresh, I received the error: "Cannot GET /profile", for example. I found a solution that involved adding code to allow the server to load routes on refresh. Ho ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Ensuring the inclusion of library licenses in the production build is a crucial step

We have numerous dependencies (node_modules) in our Angular app, which are typically licensed under Apache 2.0 or MIT. From my understanding of the licenses, the production build is considered a "derived work" and we are required to include copyright notic ...

Is there a different option similar to forkJoin for handling incomplete observables?

constructor( private route: ActivatedRoute, private http: Http ){ // Retrieve parameter changes observable let paramObs = route.paramMap; // Fetch data once only let dataObs = http.get('...'); // Subscribe to both ob ...

What is the reason behind not being able to pass an instance of B to an argument a of type T in Typescript generics when T extends B?

There is a problem with my code: class X<T extends B> [...] // this.p.a :: B | null methodA(a: T):void {[...]} methodB(): void { if(this.p.a){ // :: B this.methodA(this.p.a) // Error My intention was for T to be any type that exten ...

Testing the subscribe function in Angular within a returned Promise: A guide

I am facing an issue with a service that returns a Promise. It retrieves data from a JSON file using a subscribe method before resolving the Promise. I am trying to test the result of this Promise based on the parameters I provide, but I am encountering t ...

Encountering a module error when using SignalR with Webpack and TypeScript: 'Unable to locate module './NodeHttpClient''

I am currently working on integrating a SignalR client into an Angular application using Webpack and TypeScript. Here is the content of my package.json file: { "private": true, "version": "0.0.0", "scripts": { "test": "karma start ClientApp/tes ...

Exploring multiple states within an interval function in React Native

I'm struggling to find the right words for this question. I've encountered an issue where I need to constantly check and update a complex state object within an interval loop in my program. To simplify, let's say it consists of just a counte ...

Exploring the latest whatwg-fetch update with TypeScript version 2.5.3

Within my TypeScript project, I am currently utilizing "whatwg-fetch": "2.0.3" as the latest version of this polyfill. Additionally, for types, I am using version "@types/whatwg-fetch": "0.0.33", and everything functions smoothly when working with TypeScri ...