Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included.

I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted.

https://i.stack.imgur.com/70thi.png

Currently, our method involves using OptionSelected for mouse selection, OptionActivated for keyboard selection, and OnBlur for triggering selection when clicking out of the textbox.

I'm wondering if there might be a cleaner solution in Angular Material, or if this approach with three lines of code is the most efficient.

<mat-form-field>
  <mat-label>Document Number</mat-label>
  <input type="text"
        matInput
        formControlName="documentNumber"
        (blur)="documentNumberChangeEvent($event)"
        [matAutocomplete]="auto"
  >
  <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" 
    (optionActivated) = "documentNumberChangeEvent($event)"
    (optionSelected)="documentNumberChangeEvent($event)"
  >

Answer №1

One possible improvement could be to utilize the FormControl valueChanges property:

...
@Component(...)
export class AutocompleteSimpleExample {
  readonly documentNumber = new FormControl();
  readonly options: string[] = ['One', 'Two', 'Three'];

  constructor() {
    this.documentNumber.valueChanges.subscribe(value => {
      console.log(value);
    });
  }
}

Check it out on StackBlitz

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

There are occasional instances of phone skipping functions within a loop in Ionic 4

My POS app is designed to work with a thermal printer using the Bluetooth Serial plugin. The issue I am facing is that when the order is too long, I divide the invoice into 300-bit chunks. This process works flawlessly on my phone every time, but when I at ...

Utilize only the necessary components from firebase-admin in Cloud Functions with Typescript

When I looked at my transpiled code from cloud functions, I noticed the following TypeScript import: import { auth, firestore } from 'firebase-admin'; It gets transpiled to: const firebase_admin_1 = require("firebase-admin"); Upon further exa ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

The unexpected behavior of rxjs withLatestFrom

import { of, Subject, interval } from 'rxjs'; import { tap, startWith, map, delay, publishReplay, publish, refCount, withLatestFrom, switchMap, take } from 'rxjs/operators'; const source$ = new Subject(); const res ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Looping through an array of nested objects using Vue

I have encountered a challenge with accessing specific data within an array that I am iterating over. The array is structured as follows, using Vue.js: companies: [ name: "company1" id: 1 type: "finance" additionalData: "{& ...

The Typescript decorator is unable to access the property type within its own scope

I am currently in the process of developing a dependency injector for use in my VUE js project. Recently, I created an Inject decorator with the intention of accessing a property type. It was functioning perfectly fine yesterday, but now it seems that som ...

Modifying the value upon saving in Adonis JS model

Using Adonis js I am facing an issue when trying to convert an ISO string to Datetime while saving data (the opposite of serializing DateTime fields to ISO string). I cannot find a way to do this in the model, like I would with a mutator in Laravel. Whene ...

Is Angular mat-icon undergoing a "transformation"?

Overview: The material icon I am using is the "+" sign to represent adding a new item on a webpage. While it displays correctly in English, the Spanish version of the site shows "ñ" instead. Inquiry: Should I leave the tags empty or remove the translati ...

In Angular 2, property binding will not function properly when attempting to bind to an object

I have encountered a strange issue with Angular 2 property binding. Let's start with the Store class: export class Store { id: number; name: string; address: string; } This is the component code snippet: export class MyBuggyComponent i ...

Using @ViewChildren in Angular 2 for creating recursive components

I am working on a recursive component that showcases tag A. Firstly, there is the parent component - HTML <div class=" suggestions" style="display : inline-block;" tabindex=-1 #autocompleteDiv> <span style="width: auto;cursor: pointer;posit ...

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

passing data through URL in Angular 7

Looking to pass a parameter in the URL while using Angular 7, to achieve a format like example.com/search/users?q=tom. Below is the syntax I am currently using in my service: public searchUsers(obj):any{ return this._http.get('example.com/s ...

Ways to access the value of the parent observable?

I've been exploring the concept of nesting HTTP requests using mergeMap. The API I'm working with sends data in parts, or pages, which means I have to make more requests based on the total number of pages. To determine the number of pages, I alw ...

The Art of Typing in TypeScript Classes

I am working with an interface or abstract class in TypeScript, and I have numerous classes that implement or extend this interface/class. My goal is to create an array containing the constructors of all these subclasses, while still ensuring that the arra ...

Utilizing nested observables for advanced data handling

Consider the following method: public login(data:any): Observable<any> { this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => { return this.http.post('https://api.myapp.com/login', data); }); } I want to ...

Troubleshooting the issue with the AWS CodeBuild SAM esbuild integration not functioning

I currently have a Lambda's API Gateway repository in CodeCommit that I successfully build using esbuild with CLI (SAM BUILD and then SAM DEPLOY). Now, I am looking to streamline the building process by integrating it with CodePipeline. I started exp ...

Encountering Error TS2411 when upgrading from Typescript version 1.0.0 to 1.1.0-1

After updating my TypeScript using npm install typescript -g, I have been encountering a recurring error during compilation. Although the compilation is successful, it's becoming tedious. cmd.exe /D /C C:/Users/Vado/AppData/Roaming/npm/tsc.cmd --sour ...

Strategies for eliminating nested subscriptions in the search for names

I need assistance with refactoring a component I created to search for GitHub users by login. The current implementation contains nested subscribe blocks, and I would like to rewrite it using rxjs operators without nesting them. You can find the live exam ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...