I would like to get a console.log() once the scrollbar in the dropdown reaches bottom to implement infinite scrolling / “load more” feature:
On the code below, I created a ScrollEndDirective
directive which will just emit to component file:
export class ScrollEndDirective {
@Output() scrolledToEnd = new EventEmitter<boolean>();
constructor(private el: ElementRef) {
console.log('constructor logger'); // <- this is logging
}
@HostListener('scroll', ['$event'])
onScroll(event: Event): void {
const element = this.el.nativeElement as HTMLElement;
console.log(element); // <-- this is not even logging
if (element.scrollHeight - element.scrollTop === element.clientHeight) {
this.scrolledToEnd.emit(true);
} else {
this.scrolledToEnd.emit(false);
}
}
}
below is the component file:
@Component({
selector: 'nz-demo-auto-complete-options',
template: `
<div class="example-input">
<input
placeholder="input here"
nz-input
[(ngModel)]="inputValue"
(input)="onInputChange($event)"
[nzAutocomplete]="auto"
/>
<nz-autocomplete #auto scrollEnd (scrolledToEnd)="onScrollEnd($event)">
<nz-auto-option *ngFor="let option of options" [nzValue]="option.name">{{ option.name }}</nz-auto-option>
</nz-autocomplete>
</div>
`,
})
export class NzDemoAutoCompleteOptionsComponent {
inputValue?: string;
options: string[] = [];
private searchSubject = new Subject<string>();
constructor(private http: HttpClient) {
this.searchSubject
.pipe(
// debounceTime(1000), // debounce for 1 second
switchMap((value) => this.search(value))
)
.subscribe((options) => {
this.options = options;
});
}
onInputChange(event: Event): void {
const value = (event.target as HTMLInputElement).value;
this.searchSubject.next(value);
}
search(value: string) {
return this.http
.get<string[]>('https://jsonplaceholder.typicode.com/users')
.pipe(map((response) => response));
}
onScrollEnd(atEnd: boolean): void {
console.log('Scrollbar is at the end');
}
}
As you can see, directive is added to component nz-autocomplete
. It is a ng-zorro Autocomplete component (https://ng.ant.design/components/auto-complete/en).
Reason why I decided not to use ng-zorro’s Select where infinite loading is directly built-in to it:
- I don’t like the input to display
NotFoundContent
when user clicks and empty input field. If no input value, just focus on input and show nothing (how ng-zorro’s Autocomplete works). I would like to only display it when there are no actual results.
- I want the currently selected/inputted text to retain on the field. In ng-zorro’s Select, whenever user selected, you cannot delete previously inputted text. In image below, I want to clear the “apple” text but it does not allow me to as it becomes a
placeholder now
I would also appreciate if you can help me tweak ng-zorro’s Select to my liking if its easier. Thank you.
Stackblitz link to my repo: https://stackblitz.com/edit/angular-awrmdb-4dhtrr