How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature.

Now I am attempting to have the data appear in the dropdown as soon as the user clicks on the textbox, without the need for user typing. After the data is displayed, the user can filter it using the autocomplete feature.

component.html

        <div class="form-field col-lg-12">
        <label class="label" for="message">Headline</label>
        <div class="spinner-border" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <input [(ngModel)]="articleTitleKeyUp" (ngModelChange)="keyUpArticle(articleTitleKeyUp)" name="article"
            class="input-text js-input" type="text" required autocomplete="off">


        <div class="search-result" *ngIf="articles" style="max-height: 100px;">
            <ul style="margin:0; padding:5px; max-height: 100px;">
                <li *ngFor="let article of articles">
                    <a (click)="onClickArticle(article)">{{article.Title}}</a>
                </li>
            </ul>
        </div>
    </div>

component.ts

    ngOnInit(): void {
 

    /* Call API for publications on page load */

    this.article.postPublication(null).subscribe((data: any) => {
      this.allPubs = data.result;
      console.log(this.publications);
    });
  }

  onFocusPublication() {
    console.log(this.selectedDate);
  }

  /* POST article with PUB id and Date */

  keyUpPublication(e) {
    let k = e as string;
    let kl = k.length;

    this.publications = this.allPubs.filter((p) => {
      // let title = p.Title.toLowerCase()
      // return title.substring(0, kl) == k.toLowerCase()

      let title = p.Title + ' -' + p.city;
      return title.toLowerCase().includes(k.toLowerCase());
    });
  }

  onClickPublication(pub: IPub) {
    this.pubTitleKeyUp = pub.Title + ' -' + pub.city;
    this.selectedPub = pub;
    this.publications = [];
  }

  /* POST article with PUB id and Date */

  keyUpArticle(e) {
    if (!this.selectedPub) {
      return alert('Please select a Date and publication first!');
    }

    let k = e as string;
    let kl = k.length;

    if (this.allArticles?.length) {
      return (this.articles = this.allArticles.filter((p) => {
        let title = p.Title.toLowerCase();
        return title.substring(0, kl) == k.toLowerCase();
      }));
    }
    
    this.isLoading = true;

    this.article
      .postArticlesData({
        pubid: this.selectedPub.PubId,
        pubdate: this.selectedDate,
      })
      .subscribe(
        (data: any) => {
          this.isLoading = false;
          this.allArticles = data.result || [];

          this.articles = this.allArticles.filter((p) => {
            let title = p.Title.toLowerCase();
            return title.substring(0, kl) == k.toLowerCase();
          });
        },
        (e) => {
          this.isLoading = false;
        }
      );
    
  }

  onClickArticle(article) {
    this.articleTitleKeyUp = article.Title;
    this.selectedArticle = article;
    this.articles = [];
  }

  onPubChange() {
    console.log(this.selectedDate, this.selectedPub);
  }

  onSubmit() {
    if (this.selectedArticle && this.selectedDate && this.selectedPub) {
      this.router.navigateByUrl(
        'delete-article/' + this.selectedArticle.ArticleID
      );
    } else {
      alert('Please select Caldendar, and then Publication');
    }
  }
}
 

Answer №1

Follow the code snippet provided below:

ngOnInit() {
    this.getLookup();
}

In the getLookup() function, write the following code to fetch data from a WEB API:

public getLookup(){
    this.isLoading = true;

    this.article
      .postArticlesData({
        pubid: this.selectedPub.PubId,
        pubdate: this.selectedDate,
      })
      .subscribe(
        (data: any) => {
          this.isLoading = false;
          this.allArticles = data.result || [];

          this.articles = this.allArticles.filter((p) => {
            let title = p.Title.toLowerCase();
            return title.substring(0, kl) == k.toLowerCase();
          });
        },
        (e) => {
          this.isLoading = false;
        }
      );
}

Your lookup value is now filled with the data retrieved. Simply click on autocomplete to display the values.

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

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

Encountering a CORS problem when an Angular application communicates with a .NET Core API integrated with the Sustainsys.Saml2 library and Azure Active Directory serving as the Identity

Our team is currently working on implementing SAML authentication in a .NET Core API to handle requests coming from an Angular application. We are utilizing the package Sustainsys.Saml2.AspNetCore2 (version 2.9.2) for .NET 6, and we have successfully set u ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

Tips for generating search engine optimized URLs with category/subcategories/article slug in an Angular application

Currently, I am utilizing Angular 8 Version to develop a news application. My objective is to showcase the link in the following format: www.domain.com/category/category/title and www.domain.com/category. Can you guide me on how to accomplish this task? T ...

"Exploring Angular 2: Understanding the Distinction Between Modules and

I'm struggling to understand why Angular2 has two separate concepts. Module Component What exactly sets them apart and what purpose does each serve? Under what circumstances should I create a SubModule? When is it necessary to create a SubCo ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

Utilizing an Angular Service within the main.ts script

My main.ts file currently has the following code snippet: declare const require; const translations = require("raw-loader!./locale/messages.de.xlf"); platformBrowserDynamic().bootstrapModule(AppModule, { providers: [ { provide: TRANSLATIONS, useVa ...

How can one access a dynamically generated element in Angular without using querySelector?

Currently in the process of developing my custom toastr service, as shown in the GIF below My Objective: https://stackblitz.com/edit/angular-ivy-tgm4st?file=src/app/app.component.ts But without using queryselector. It's recommended to avoid querysele ...

In Angular2, the derived class can inherit decorators

Within my Angular application, I am utilizing the BaseComponent which has a specified template. My goal is to use this same template HTML in a component that extends the base one. However, I am aware that class inheritance in Angular2 only applies to cla ...

How to prevent Cut, Copy, and Paste actions in a textbox with Angular 2

I am currently utilizing Angular2 to prevent copying and pasting in a textbox. However, I am seeking guidance on how to create a custom directive that can easily be applied to all text fields. Here is the code snippet that successfully restricts the copy ...

Having difficulty handling text overflow in Angular4 and HTML

I'm facing an issue with displaying a very large text in a table. Despite trying various attributes such as - { text-overflow: clip; } { text-overflow: ellipsis; } { text-overflow: ellipsis-word; } { text-overflow: "---"; } { text-overflow: ellip ...

The timestamps I generate are based on the day following the date

While creating a schema and using {timestamps:true} in Mongo, the fields 'createdAt' and 'updateAt' are supposed to be automatically generated. However, I have noticed that when creating a document with this setup, the day of the date i ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

Utilizing Angular to Build a Single Router with Numerous Components

Within my Angular application, I am facing a challenge with two components: DashboardComponent and LoginComponent. When a user accesses the URL http://localhost:4200, I need to display the LoginComponent if the user is not logged in. However, if the user i ...

What is the method to adjust the color of <pagination-controls>?

Seeking assistance with customizing the color of angular pagination from blue to a different hue. Any suggestions? https://i.stack.imgur.com/JjcWk.png I've experimented with various code snippets, but unfortunately, none have yielded the desired res ...

Having trouble obtaining React 15.6.1 type definitions: "ERROR: Repository not found."

Trying to set up the type definitions for React 15.6.1, but encountering an error: $ npm install --save @types/react npm ERR! git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88efe1fcc8efe1fce0fdeaa6ebe7e5">[email&# ...