简体   繁体   中英

How to stop or disable ngbTypeahead input field from opening on focus until it finishes mapping all the data

I need the typeahead to show the first 5 results when clicked on the input field. I have already made a solution using the ngbTypeahead documentation .

app.component.html

<div class="form-group g-0 mb-3">
  <input id="typeahead-prevent-manual-entry" type="text" class="form-control"
  placeholder="Big dataset"
  formControlName="bigDataset"
  [ngbTypeahead]="search"
  [inputFormatter]="valueFormatter"
  [resultFormatter]="valueFormatter"
  [editable]="false"
  [focusFirst]="false"
  (focus)="stateFocus$.next($any($event).target.value)"
  (click)="stateClick$.next($any($event).target.value)"
  #instance="ngbTypeahead" />
</div>

app.component.ts

type BigDataset: {
  id: string,
  name: string
}

export class AppComponent implements OnInit {
  dataset: BigDataset[];

  @ViewChild('instance', {static: true}) instance: NgbTypeahead;
  focus$ = new Subject<string>();
  click$ = new Subject<string>();

  constructor(
    private formBuilder: FormBuilder,
  ) { }

  ngOnInit(): void {
    this.dataForm = this.formBuilder.group({
      bigDataset: ["", [Validators.required]],
    });
  }

  getBigDataset() {
    //Excluded for simplicity. This returns a set of objects (~3000)
    //of type BigDataset and assigns it to this.dataset.
  }

  valueFormatter = (value: any) => value.name;

  search: OperatorFunction<string, readonly BigDataset[]> = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(100), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(map(term => (term === '' ? this.dataset
        : this.dataset.filter(data => data.name.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 5))
    );
  };
}

Now this works . However, the problem is if I click on the input field immediately after the page initialisation, I get this error:

ERROR TypeError: Cannot read properties of undefined (reading 'slice')
    at org-address.component.ts:93:109
    at map.js:7:1
    at OperatorSubscriber._next (OperatorSubscriber.js:9:1)
    at OperatorSubscriber.next (Subscriber.js:31:1)
    at subscribe._OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.OperatorSubscriber.innerComplete (mergeInternals.js:25:1)
    at OperatorSubscriber._next (OperatorSubscriber.js:9:1)
    at OperatorSubscriber.next (Subscriber.js:31:1)
    at Subject.js:31:1
    at errorContext (errorContext.js:19:1)
    at Subject.next (Subject.js:26:21)

From what I can understand this is because the typeahead tries to show data before it finishes the map function. The problem is the time it takes to map can increase if I decided to increase the dataset, so waiting an unknown amount of time until it finishes the process is not an option. I would like to disable the field or use another solution until it finished the mapping process.

I have tried disabling the form field and enabling it after the mapping process using finalize(), but I seem to have made a mistake and the field stays disabled.

search: OperatorFunction<string, readonly BigDataset[]> = (text$: Observable<string>) => {
    this.dataForm.get('bigDataset')?.disable();
    const debouncedText$ = text$.pipe(debounceTime(100), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
      finalize(() => this.dataForm.get('bigDataset')?.enable()),
      map(term => (term === '' ? this.dataset
        : this.dataset.filter(data => data.name.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 5))
    );
  };

Any help regarding this would be greatly appreciated.

A friend of mine actually gave me a very simple fix for this, which was to add optional chaining after data filtering (before the splicing process). Adding '?' before calling the slice method worked like a charm and stopped giving an error if it tried returning the value before the filtering process is completed.

search: OperatorFunction<string, readonly BigDataset[]> = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(100), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(map(term => (term === '' ? this.dataset
        : this.dataset.filter(data => data.name.toLowerCase().indexOf(term.toLowerCase()) > -1))?.slice(0, 5))
    );
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM