Activate the typeahead feature in ng-bootstrap 4 by setting it to open when the

I am currently using ng-bootstrap 4 (beta 8) and have the following setup:

<ng-template #rt let-r="result" let-t="term">
    {{ r.label }}
</ng-template>

<input
        id="typeahead-focus"
        class="form-control"
        [(ngModel)]="model"
        [ngbTypeahead]="search"
        [inputFormatter]="formatter"
        [resultTemplate]="rt"
        (focus)="focus$.next($event.target.value)"
        (click)="click$.next($event.target.value)"
        #instance="ngbTypeahead"
/>

I now want to trigger the opening of the typeahead when the user clicks on the input element. How can I achieve this?

this.search = (text$) =>
    text$
        .map(term => (term === '' ? this.items : this.items.filter(v => v.label.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10));

this.formatter = (x: {label: string}) => {
    console.log(x);
    return x.label;

Answer №1

This particular solution has proven effective for me:

Simply add the onFocus event to the input search field

Within my.html:

 <input 
    (focus)="onFocus($event)" 
    type="text" 
    (selectItem)="onItemSelected($event)" 
    [(ngModel)]="myModel" 
    [ngbTypeahead]="search" 
    [resultTemplate]="rt" 
    [inputFormatter]="formatter"/>

Within my.ts:

  public onFocus(e: Event): void {
    e.stopPropagation();
    setTimeout(() => {
      const inputEvent: Event = new Event('input');
      e.target.dispatchEvent(inputEvent);
    }, 0);
  }

  search = (text$: Observable<string>) =>
    text$
      .debounceTime(200)
      .distinctUntilChanged()
      .map(term => this.myList
          .filter(v => this.myfilter(term))
          .slice(0, 10));

For additional insights, refer to Typeahed: allow search on focus #698

Answer №2

Based on the latest guidelines, it is recommended to utilize the following HTML:

<input id="typeahead-focus" type="text" class="form-control" [(ngModel)]="model"  [ngbTypeahead]="search" (focus)="focus$.next($event.target.value)" (click)="click$.next($event.target.value)" #instance="ngbTypeahead"/>

along with the following code snippet:

  @ViewChild('instance') instance: NgbTypeahead;
  focus$ = new Subject<string>();
  click$ = new Subject<string>();

  search = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

  return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
    map(term => (term === '' ? states
       : states.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))
  );

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

determining the preference between setTimeout and setImmediate

After reading the documentation on the node, it mentions: setImmediate(callback, [arg], [...]) This function is supposed to execute callback immediately after I/O events callbacks and before setTimeout and setInterval However, in practice, I noticed tha ...

Leveraging the power of both IntelliJ and AngularCLI 6 to effortlessly import libraries using their package names

My Angular CLI 6 project consists of two components: A library containing services and components A project that utilizes this library When integrating the library into the frontend project, I typically use: import { SomeLibModule } from "some-lib"; H ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Ways to implement standard sorting in react-table

Currently, I am utilizing react-table v7 to generate tables. You can find more information about react-table at https://www.npmjs.com/package/react-table. While working with the table, I was able to implement sorting for all columns by following this e ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Adding a project to TFS source control using Visual Studio Code: a step-by-step guide

Looking for guidance on adding an Angular 4 project developed with Visual Studio Code (version 1.18.0) to TFS source control. I've already installed the TFS extension (version 0.6.0) in Visual Studio Code, but unsure how to map the project folder to T ...

Error Encountered in Cypress: "Tried to wrap warn but it is already wrapped"

Objective: Utilize Cypress and Typescript to test for warnings and errors on the console. Error Encounter: An attempt was made to wrap warn, which is already wrapped. Snippet: describe.only("Unauthenticated User", () => { it("No C ...

Enhance Angular's User Interface using the Express Backend

I am a beginner in the MEAN stack development. I have set up an express server (api) that listens at a specific URL and handles incoming data. My goal is to create a frontend for this API where I can send and display incoming data, logs, and current proc ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

Leveraging AJAX for transferring variable from a dynamic HTML table to PHP for executing an update query

Is there a way to insert a value into the input field valor and update the respective row with that value using both the ID and the valor in the update query? I seem to be missing something here, what could it be? Table <?php $IDTipoEquipamento = ...

A helpful guide on using workbox to effectively cache all URLs that follow the /page/id pattern, where id is a

Looking at this code snippet from my nodejs server: router.get('/page/:id', async function (req, res, next) { var id = req.params.id; if ( typeof req.params.id === "number"){id = parseInt(id);} res.render('page.ejs' , { vara:a , va ...

Is it possible to execute a standalone .js file using Node.js and Express?

I am working on a Node.js/Express project and I need to test a specific file containing a single function. Currently, I have been calling this function in the index.js file and running all functions within it by using `npm run dev`. However, I would like t ...

Displaying a loading progress bar while the website is being loaded using Javascript

Currently working on developing a GUI site, I am looking to implement a progress bar. However, I require some JavaScript code that can detect the loading status of the site along with the number of elements/images that have been loaded so far, as well as d ...

Angular-meteor tutorials have a method known as '/parties/insert' that is already clearly defined and explained

I am currently diving into meteor + angular and enjoying learning through ! As I was working on the 3-way data binding section, I created a folder named collections within the socially folder. In this folder, I made a file called parties.ts where I added ...

Utilizing Gulp locally without the need for global installation or referencing the bin js file

I have a gulpfile.js that runs perfectly when I type 'gulp' into the command line. Essentially, the 'gulp' bash command just calls the specific js file outlined in 'package.json >> bin >> gulp' of the globally ins ...

Unspecified variables in a Javascript bot

Currently, I am working on a project involving the Kik API to create a bot. The main goal is for the game to initiate when users type "!hangman". A boolean value called hangman activates this process and then becomes inactive. Players can then input "!ha ...

The jQuery date picker is showing an error with the function daySettings[2].replace, indicating that

Encountering a problem with the jQuery version I am using: <script src="js/Common/jquery-2.1.1.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> The code I have writte ...