Display a dropdown menu in Angular when the "@" symbol is typed into an input field

I am trying to achieve the functionality where a dropdown menu is displayed when @ is typed in the input field.

The Custom Component

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith('@'),
        map(val => val.length >= 1 ? this.filter(val): [])
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
    console.log(this.options)
  }

Although I have implemented the above code, unfortunately it is not functioning as expected.

HTML

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input #inputField type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

Answer №1

Your subscription is going smoothly.

Just a reminder, be sure to escape the @ in the filter function because there isn't an @ in your option List.

Give this a try:

filter(val: string): string[] {
  return this.options.filter(option =>
    option.toLowerCase().indexOf(val.toLowerCase().replace('@', '')) === 0);
}

Answer №2

To listen for changes on your input, simply use the change event like so:

(change)='handleEvent($event)'

When the input changes, check if it contains the @ symbol and take appropriate action.

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

Is there a way to modify the Firebase DB without relying on push keys?

After reading a tutorial, I learned about using push keys to generate unique push ids. However, I prefer using my own unique key for set or update instead of relying on push keys. Am I missing something here? Your input would be greatly appreciated. Than ...

Prevent selection of specific weekdays in Kendo grid calendar

When editing a record in a Kendo grid with a date field, is there a way to only allow the selection of Monday and disable all other days of the week? ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

Do identical files stored in separate locations produce unique sha1 hashes?

var crypto = require('crypto'); var fs = require('fs'); var file1 = process.argv[2]; var file2 = process.argv[3]; var sha1sum = function(input){ return crypto.createHash('sha1').update(JSON.stringify(input)).digest(' ...

Adjust image loading according to screen dimensions

I am working on HTML code that currently displays an image. The code looks like this: <div> <img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" /> </div> My goal is to show a different image based on the screen si ...

What is the process for modifying information within a text document?

What I am trying to achieve is a ticker with two buttons that can increment or decrement the value by one each time they are clicked. In addition, I want this value to be synced with a number stored in a text file. For instance, if both the counter and t ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Utilizing the require pattern to integrate JavaScript functionality into HTML

Have: project |- consume_script.js |- index.html Need index.html to be like: <html> <head> </head> <body> <script src="consume_script.js"></script> </body> </html> Issue: consume_script ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

Repeatedly Triggered JQuery AJAX Calls

On my web page, I have implemented a feature that allows users to search for an address using a GIS server's web-service. This functionality is triggered by a button click event which calls a JQuery AJAX method. Upon successful retrieval of address da ...

Loading images in advance before webpage loads

Welcome friends! This is my first time asking a question here, so I hope I'm doing it right :) I'm looking to preload 3 images before the webpage fully loads so that they all appear simultaneously. Currently, the images load one after another and ...

Adjust the HTML layout based on the JSON data provided

I am working with a JSON script that contains live matches, which change every 5 minutes. The changes could involve keys such as live_in or score. Matches are also being deleted and added to the JSON. I want to ensure that my HTML output remains updated at ...

Is there a way to configure the URL so that I can open my pdf object of Teamcenter Active Workspace (AWS) exclusively in the view window of the explorer browser through a link?

My organization's TC Active Workspace version is above 4.0 (AWS) and the URL link is structured like this: http://:Port/#/com.siemens.splm.clientfx.tcui.xrt.showObject?uid= . I am looking to specifically open a PDF in Browser View. The object I am re ...

Can React components receive props or data when they are inserted into regular HTML code?

I have a project where I need to make updates to an old-fashioned website. The current layout is table-based and coded by hand. My idea to streamline the process is to use React to minimize repetitive coding tasks. Specifically, I want to loop through an a ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

Incorporate the {{ }} syntax to implement the Function

Can a function, such as toLocaleLowerCase(), be used inside {{ }}? If not, is there an alternative method for achieving this? <div *ngFor="let item of elements| keyvalue :originalOrder" class="row mt-3"> <label class=" ...

"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API. Here is the script I am using for the post: //Creating Order const createOrder = async (data) => { try { co ...

What is the best way to execute the Angular build output (dist folder, artifact)?

After creating an Angular build for my app using the command: $ ng build I uploaded the result to my remote server: https://i.sstatic.net/9O7fZ.png On the server, I have also installed the necessary node version and Angular CLI. However, when I att ...

Is it possible to scroll down a page using Javascript/jQuery?

Is there a way to implement a "page down" action using Javascript/jQuery that functions correctly even if the user has adjusted their zoom settings? In other words, I need it to scroll exactly as much as it would if the user physically pressed the key for ...