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

Showing elements from an array after adding new items with Ionic and Angular 2 on click

Struggling to update an array using the push method and showcase it in the view? Frustrated that the new value from a text box isn't displaying on the view as expected? If you're puzzled by why all you see is an empty row with no value from the t ...

md-select doesn't reflect changes in the model when using key-value parameters

I am facing an issue with my predefined model (selectedVegetables) in connection with an md-select. It appears to be not functioning properly when the model already contains a key and value pair. You can view the code sample here: Code Pen. Here is a snip ...

Exploring Dependency Injection in Angular2: A Comparison of TypeScript Syntax and @Inject Approach

I'm currently working with Angular2 build 2.0.0-alpha.34 and I can't figure out why I'm getting different results from these two code snippets. The only variation is between using @Inject(TitleService) titleService and titleService: TitleSe ...

Error message: "ReferenceError occurred while trying to access the Data Service in

As I embark on the journey of creating my very first MEAN stack application - an online cookbook, I have encountered a challenge in Angular. It seems like there is an issue between the service responsible for fetching recipe data from the API (RecipeDataSe ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

Angular positions the <style> element following the custom stylesheet <link>

I need help understanding Angular styling. Currently, I am working with Angular 10 and Prime-ng. I have created a custom style to override a Prime-ng component's style. However, when I serve the app for testing, the custom style does not override it ...

We are in the process of migrating Angular from version 7 to 16, however, we are facing an issue where one of the libraries is still stuck on version 5, causing a Module not found error related to 'rxjs-com

We recently upgraded an Angular project from version 7 to 16 and we are currently using "rxjs": "~7.8.0". Interestingly, there is no mention of rxjs-compat in the package.json file either. However, during the building process of the application, we encoun ...

Customizing themes in Angular 4

My app allows users to select 4 colors: Brand Accent Contrast Accent Light These color choices are saved in the user's account, and I retrieve and store this data upon login. I am looking for a way to apply these color choices as a global theme ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Enhance your Angular Material Table with split headers and sticky header capabilities

I am having an issue with the header of my Angular Material table. I need help adding a sticky header feature. I tried using sticky: true, but it's not working for my first column since I have hidden it. Additionally, the first row is displaying the ...

How to convert an attribute of an object within a list to a string separated by commas in TypeScript and Angular

I am working with an array of person objects in Angular 5 and displaying them in HTML using ngFor. The Person objects also contain an array of Role objects. persons:Array<Person>=[]; Each Role object is structured like this: export class Role{ ...

Generate a type error if the string does not correspond to the key of the object

How can I trigger a type error in TypeScript 4.4.3 for the incorrect string 'c' below, which is not one of the keys of the object that is passed as the first parameter to the doSomething method? const doSomething = ({ a, b }: { a: number, b: stri ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

Which objects can be looped through in Aurelia templating?

In the documentation for Aurelia, it mentions that repeaters can be used with arrays and other iterable data types, including objects, as well as new ES6 standards like Map and Set. Map is usually recommended, as shown in the example below: <template&g ...

Ways to eliminate the dynamically included angular files from the .net core web api project

Embarking on a new project, I aim to utilize asp.net core web.api and angular 9. My initial goal is to establish a .net core web api project without MVC or scaffolded angular project. What I desire is to have the spa launch along with the web.api, mirrorin ...

Next.js API routes encountering 404 error

I am encountering an issue with calling my route API (404) in my new nextjs project. The route API can be found at src/app/api/speed.js Within my page src/app/page.tsx, I have the following code snippet: fetch("api/speed").then(res=>res.json ...

Display notification if the request exceeds the expected duration

Is there a way to display a message when a request is taking too long? For instance, if the request exceeds 10 seconds in duration, I want to show a message asking the user to wait until it finishes. fetchData(url, requestParams) { return this.restServic ...

Tips for verifying the auto complete feature within an angular stepper component

<form [formGroup]="assetformGroup" (ngSubmit)="onSubmit('update')" #formone="ngForm"> <mat-horizontal-stepper labelPosition="bottom" [linear]="true" #stepper formArrayName="formArray"> <mat-step formGroupNam ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

Using Typescript, instances of a class can access its members from within methods without needing

Having recently dipped my toes into the world of Node and TypeScript, I was taken aback to discover that you need to explicitly specify this in order to access class members when working with classes. Take for example this code snippet: class MyClass { p ...