问题
Where can I find the angular extension for infinite scrolling of the autocomplete input (for example, https://select2.org/data-sources/ajax)? I have an API with pagination and must capture other objects when the user scrolls down
回答1:
Infinite scroll for angular material 2 autocomplete
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="State" aria-label="State" [matAutocomplete]="statesAutocomplete" [formControl]="stateCtrl">
<mat-autocomplete #statesAutocomplete="matAutocomplete" (opened)="autocompleteScroll()">
<mat-option *ngFor="let state of filteredStates" [value]="state.name">
<img class="example-option-img" aria-hidden [src]="state.flag" height="25">
<span>{{state.name}}</span> |
<small>Population: {{state.population}}</small>
</mat-option>
</mat-autocomplete>
</mat-form-field>
<br>
</form>
@ViewChild('statesAutocomplete') statesAutocompleteRef: MatAutocomplete;
@ViewChild(MatAutocompleteTrigger) autocompleteTrigger: MatAutocompleteTrigger;
autocompleteScroll() {
setTimeout(() => {
if (
this.statesAutocompleteRef &&
this.autocompleteTrigger &&
this.statesAutocompleteRef.panel
) {
fromEvent(this.statesAutocompleteRef.panel.nativeElement, 'scroll')
.pipe(
map(x => this.statesAutocompleteRef.panel.nativeElement.scrollTop),
takeUntil(this.autocompleteTrigger.panelClosingActions)
)
.subscribe(x => {
const scrollTop = this.statesAutocompleteRef.panel.nativeElement
.scrollTop;
const scrollHeight = this.statesAutocompleteRef.panel.nativeElement
.scrollHeight;
const elementHeight = this.statesAutocompleteRef.panel.nativeElement
.clientHeight;
const atBottom = scrollHeight === scrollTop + elementHeight;
if (atBottom) {
// fetch more data
this.filteredStates = [...this.filteredStates, ...this.states]
}
});
}
});
}
stackblitz link
来源:https://stackoverflow.com/questions/46347435/infinite-scroll-for-autocomplete-input-in-angular-2