问题
I am using NgbTypeahead component of ng-bootstrap. My problem is, when I put the typeahead component inside a scrollable component and make a scroll down, the position of dropdown container doesn't change.
<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>
It could be a small CSS issue but I could not find the solution.
Here is the plunkr : http://plnkr.co/edit/rxOhDy72YWlLy9U4Ujcd?p=preview
Type in a character in the text box and then scroll up-down
回答1:
As NgbTypeahead does not have support with scroll, we need to handle from component. Use showDropdownEle function on 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);
}
}
}
}
来源:https://stackoverflow.com/questions/47574449/ngbtypeahead-component-doesnt-scroll-inside-a-scrollable-component