ng-select大量數據導致卡頓問題修復 二次簡易封裝

html部分

 

<div class="sd-select">
    <nz-select [nzMode]="nzMode|| 'default'" [(ngModel)]="value" [nzAllowClear]="nzAllowClear || true"
        [nzPlaceHolder]="nzPlaceHolder || ''" (nzOpenChange)="updateCouponList($event)"
        [nzShowSearch]="nzShowSearch || false" (ngModelChange)="handleOnChange($event)" (nzOnSearch)="onSearch($event)"
        (nzScrollToBottom)="scrollToBottom()">
        <nz-option *ngFor="let option of showOptions" [nzLabel]="!!optionLabel? option[optionLabel]: option"
            [nzValue]="!!optionValue?option[optionValue]: option">
        </nz-option>
    </nz-select>
</div>

  

 

ts部分

 

import { Component, OnInit, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    selector: 'sd-select',
    styleUrls: ['./select.component.less'],
    templateUrl: './select.component.html',
    preserveWhitespaces: false,
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        multi: true,
        useExisting: forwardRef(() => SelectComponent)
    }]
})
export class SelectComponent implements OnInit, ControlValueAccessor {
    @Input() nzMode: 'multiple' | 'default';
    @Input() nzAllowClear?: boolean;
    @Input() nzShowSearch?: boolean;
    @Input() nzPlaceHolder?: string;
    @Input() options: Array<any>;
    @Input() optionLabel: string;
    @Input() optionValue: string;

    value = null;
    pageNum = 0;
    pageSize = 20;
    showOptions = [];
    inputValue = [];

    onChange: (value: string | string[]) => void = () => null;
    onTouched: () => void = () => null;

    constructor(
    ) { }

    handleOnChange($event) {
        this.onChange($event);
    }

    writeValue(value: any): void {
        this.value = value;
    }

    registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

    ngOnInit() {

    }

    onSearch(str) {
        if (!str) return;
        this.showOptions = this.options.filter(item => item.indexOf(str) !== -1);
    }

    scrollToBottom() {
        if (this.pageNum > Math.ceil(this.options.length / this.pageSize)) return;
        this.pageNum++;
        this.showOptions = [...this.options.slice(0, this.pageNum * this.pageSize + this.pageSize)];
    }

    updateCouponList(state) {
        if (state) {
            this.showOptions = this.options.slice(0, this.pageSize);
        } else {
            setTimeout(() => {
                this.showOptions = [];
            }, 500);
        }
    }

}

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章