I am currently working on an Angular 2 application that utilizes PrimeNG components.
One of the UI features includes an autocomplete component with multi-select functionality (p-autoComplete
) similar to the one showcased in the official documentation:
<p-autoComplete [(ngModel)]="countries"
[suggestions]="filteredCountriesMultiple"
(completeMethod)="filterCountryMultiple($event)"
[minLength]="1"
placeholder="Countries"
field="name"
[multiple]="true">
</p-autoComplete>
In my specific case, the input field within this component has fixed dimensions and a scroll bar.
Issue:
Whenever I remove an element from the middle of the autocomplete list, the focus automatically shifts to the bottom of the input field. This behavior can be seen in the following illustration:
https://i.sstatic.net/FzLFV.gif
This shifting of focus can be quite bothersome for users, especially when there are multiple fields that need to be edited or removed.
Query: Is there a way to prevent the automatic shift in scroll position after removing an element?
How to Replicate:
To replicate this issue more accurately, you can add the following CSS properties:
max-width: 150px;
max-height: 100px;
overflow-y: auto;
directly onto the documentation page within the
ui-autocomplete-multiple-container.ui-inputtext
CSS class using your browser's console.
UPDATE:
I was able to retrieve the scroll position by implementing an onUnselect
method within the component as shown below:
onUnselect(event: any) {
document.querySelector("div.my-input-class").scrollTop
}
UPDATE 2: It is now functional!
The solution involved utilizing both the onUnselect
and onFocus
event handlers.
Firstly, I saved the last scroll position within the onUnselect
method.
Secondly, I set this saved value to the specified element during the onFocus
event.
The corresponding code snippet looks like this:
scrollPosition: number = 0;
onUnselect(event: any) {
let input = document.querySelector("div.my-input-class");
this.scrollPosition = input.scrollTop;
}
onFocus(event: any) {
let input = document.querySelector("div.my-input-class");
input.scrollTop = this.scrollPosition;
}
This solution works effectively, although it would be ideal if PrimeNG incorporated such functionality into their component by default. I find it perplexing why this feature isn't included out of the box.
If you have a better alternative solution, please feel free to suggest.