The NgbTypeahead element is not able to scroll when placed within a scrollable container

Currently, I am utilizing the NgbTypeahead component from ng-bootstrap. The issue I am facing is that when I place the typeahead component within a scrollable element and proceed to scroll down, the position of the dropdown container remains unchanged.

<div style="height: 300px;   overflow-y: auto;">
...
<input id="typeahead-template" type="text" class="form-control [(ngModel)]="model" 
       [ngbTypeahead]="search" [resultTemplate]="rt [inputFormatter]="formatter" />
...
</div>

This could potentially be a minor CSS problem that has eluded my attempts at resolving it.

For further reference, here is the link to the plunkr : http://plnkr.co/edit/rxOhDy72YWlLy9U4Ujcd?p=preview

To observe the issue firsthand, simply input a character into the text box and then proceed to scroll up and down.

Answer №1

Add the code snippet below to your styles.css file.

You have the option to insert this code in one of the following locations:

  • styles.css
  • style tag within index.html
ngb-typeahead-window {
  max-height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
}

Find the functioning code on stackblitz through this link: https://stackblitz.com/edit/angular-qpzsfv

Answer №2

If you want to incorporate a vertical scroll bar into your typeahead results, consider implementing the following code:

ngb-typeahead-window.dropdown-menu {
    max-height: 500px !important;
    overflow-y: auto;
}

Answer №3

Find the typeahead-scrollable.html file below:

<input id="typeahead-scrollable" type="text" class="form-control" (keydown)="typeaheadKeydown($event)" #typeaheadInstance="ngbTypeahead" [(ngModel)]="model" [ngbTypeahead]="search" [resultFormatter]="formatter" 

Check out the typeahead-scrollable.ts file for the corresponding TypeScript code:

    @ViewChild('typeaheadInstance')
    private typeaheadInstance: NgbTypeahead;

    typeaheadKeydown($event: KeyboardEvent) {
        // Code for handling keydown events in the typeahead
    }

    private scrollIntoViewIfNeededPolyfill(elem: HTMLElement, centerIfNeeded = true) {
        // Polyfill function to handle scrolling elements into view
    }

If you'd like to see a working example, visit this link:

Working Example on StackBlitz

Answer №4

Since NgbTypeahead lacks scroll support, we must manage it from the component. Utilize the showDropdownEle function upon keydown of Input.

private isElementInViewport(el, inputElem) {
const rect = el.getBoundingClientRect();
const rectElem = inputElem.getBoundingClientRect();
console.log(rectElem);
return (
  rect.top >= rectElem.bottom &&
  rect.left >= 0 &&
  rect.bottom <= (rectElem.bottom + rect.offsetHeight) &&
  rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

public showDropdownEle(event) {
if (event.keyCode === 38 || event.keyCode === 40) {
  if (event.target.nextElementSibling && event.target.nextElementSibling.nodeName === 'NGB-TYPEAHEAD-WINDOW') {
    let activeDropdownEle = (event.keyCode === 40) ? event.target.nextElementSibling.querySelector('.active').nextElementSibling : event.target.nextElementSibling.querySelector('.active').previousElementSibling;
    if (!activeDropdownEle) {
      const allDropdownElems = event.target.nextElementSibling.querySelectorAll('.dropdown-item');
      activeDropdownEle = (event.keyCode === 38) ? allDropdownElems[allDropdownElems.length - 1] : allDropdownElems[0];
    }
    if (!this.isElementInViewport(activeDropdownEle, event.target) && event.keyCode === 40) {
      activeDropdownEle.scrollIntoView(false);
    }
    if (!this.isElementInViewport(activeDropdownEle, event.target) && event.keyCode === 38) {
      activeDropdownEle.scrollIntoView(true);
    }
  }
}
}

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

Align a span vertically within a div

I need help aligning the content "ABC Company" vertically within a div using Bootstrap 4's alignment helper classes. Despite my efforts, I have not been successful. Here is the code I am using: <div class="container" style="width: 740px;"> < ...

Is there a way to keep a div element stationary during scrolling without using fixed positioning?

Is there a way to prevent a div from moving when scrolling up or down without using the position:fixed property? When an element is fixed, the scroll bar disappears making it impossible to reach the element by scrolling. div{ position:fixed; top:1 ...

What is the best way to ensure one div expands to full width while simultaneously hiding another div on the page?

Hey there, I'm looking for a way to expand the width of a clicked div while making the other div disappear from the screen simultaneously. It should also be toggleable, so clicking the button again will shrink the div and bring back the other one. For ...

`Can you bind ngModel values to make select options searchable?`

Is there a way to connect ngModel values with select-searchable options in Ionic so that default values from localStorage are displayed? <ion-col col-6> <select-searchable okText="Select" cancelText="Cancel" cla ...

Issue with Angular 11: Unable to bind to 'ngForOf' as it is not recognized as a valid property of 'tr' element

My issue lies with a particular page that is not functioning correctly, even though it uses the same service as another working page. The error seems to occur before the array is populated. Why is this happening? I appreciate any help in resolving this p ...

Troubleshooting Bootstrap select box design discrepancies

Currently revamping a website and encountered an unusual issue with select boxes. There seems to be an overlapping white space where the option values should be. Here's a visual reference: View Image of Select Box Issue Utilizing Bootstrap for the re ...

Encase the entire section following cloning with JQuery

Make sure to check out the jsfiddle demo linked below before proceeding: JSFIDDLE I need to transform the original structure as shown below: <div class="out"> <a>im here</a> <a>to save</a> <a>our</a> ...

The height of the div element is automatically adjusted to zero

I am dealing with a simple layout where I have a main div that floats to the left. Within this main div, I nest other divs using the clear both style. Below is a simplified version of my setup: <div id="wrapper" class="floatLeft"> <div id="ma ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...

Error message: The import from './components/headerComponent/header' failed because it does not have a default export. Make sure to export it as default to be able to import it

I've been trying to bring a header from one file into another, but it's not cooperating. import React from 'react'; import { Typography, Card, CardContent } from '@material-ui/core'; import Header from './components/head ...

The initial update of the view does not occur when a component property changes in Angular 2 RC6

I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the v ...

Discover the complete guide on incorporating a JavaScript library with additional dependencies in Angular 2

I am a beginner with angular 2 and I am attempting to integrate the Miso Dataset JavaScript library into my angular 2 project. The Miso library requires other JavaScript libraries as dependencies. Although I have included all the necessary JavaScript file ...

When using ngStyle to bind a variable, the binding variable will be null

Currently, I am attempting to utilize ngStyle to set the background image. <div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }"> The fun ...

Is there a way to determine the location where my website is fetching CSS and media files from?

After implementing Wagtail on my website, I encountered an issue with the CSS and images not being found when the site was put into production. I have already tried running python manage.py collectstatic and ensured that all of my CSS files are located in ...

ChessboardJs: JavaScript Boards Function Properly on Initial Use Only

Update: The page code can be accessed via my page URL. I'm unsure where the issue lies. Your assistance is appreciated. Issue: Initially, when clicking on the chess puzzles page, everything works fine. However, upon re-clicking from the homepage, th ...

Adjust the dimensions of an Angular Material 2 dialog by updating the width or height

Is there a way to adjust the dimensions of an open Angular Material 2 dialog, either its width or height? I attempted to modify the size of the dialog by obtaining a reference to it and using the updateSize method within the dialog. Unfortunately, I belie ...

Retrieve the value of the second child element in a table cell when clicking on it with Javascript

I have created a table with one row that includes the title of the month and a cell containing an inner table with multiple rows and cells. I want to display the content of the second cell in the second table as a modal box or alert dialog when it is click ...

Leverage variables in JavaScript to establish a unique style

function AdjustScale(){ scaleX = window.innerWidth / 1024; scaleY = window.innerHeight / 768; element = document.getElementById("IFM"); element.style.transform = "scale(" + scaleX + ", " + scaleY + ")"; } I'm facing an issue with thi ...

Troubleshooting the issue of Angular Reactive Forms Select Option not properly selecting pre-defaulted objects

One issue I am facing is with a select option dropdown that fetches its options from the back-end through an API call and sets them. While trying to have a pre-selected option on page load, setting the value does not seem to be working for me. Even attempt ...

jQuery.addClass function not functioning correctly

I am encountering an issue where the functionality in this code snippet isn't quite working as expected. Specifically, I would like the 'huh' div to become opaque when the menu is hovered over. While attempting to achieve this with fadein/ou ...