Home > database >  ng-bootstrap: open on focus
ng-bootstrap: open on focus

Time:09-28

Recently, I write code according to the office site Open on focus

Here are the main code below.

In html file:

<input 
   
  [(ngModel)]="diagnosisReport.diagnosis" 
  type="text"
  #diagnosis="ngbTypeahead"
  [ngbTypeahead]="searchDiagnosis"
  (focus)="focus$.next($any($event).target.value)"
  (click)="click$.next($any($event).target.value)"
  [disabled]="isDisabledForm" 
/>

In typescript file:

import {NgbTypeahead} from '@ng-bootstrap/ng-bootstrap';
import {debounceTime, distinctUntilChanged, filter, map} from 'rxjs/operators';
import { Observable, Subject, merge } from 'rxjs';


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

public searchDiagnosis(text$: Observable<string>): Observable<string[]> {
  const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
  const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.diagnosisInstance.isPopupOpen()));
  const inputFocus$ = this.focus$;

  return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
    map(term => (term === '' ? ['jimmy']
      : ['kimmy'])
  ));

}

But, I got error below:

ERROR TypeError: Cannot read properties of undefined (reading 'click$')
ERROR TypeError: Cannot read properties of undefined (reading 'focus$')

I try to set a timeout function to handle click$ and focus$, like:

setTimeout(() => {
  console.log(this.click$);
}, 100)

However, I get the same error ERROR TypeError: Cannot read properties of undefined (reading 'click$').

So, anyone give me a hand.

CodePudding user response:

You will need to define you function as a OperatorFunction as given in the demo so your searchDiagnosis code will look like

searchDiagnosis: OperatorFunction<string, readonly string[]>  = (text$: Observable<string>) =>{
    const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;
  
    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
      map(term => (term === '' ? ['jimmy']
        : ['kimmy'])
    ));
  
  }

Demo

Or in your html use searchDiagnosis.bind(this)

<input
  id="typeahead-focus"
  type="text"
  
  [(ngModel)]="model"
  [ngbTypeahead]="searchDiagnosis.bind(this)"
  (focus)="focus$.next($any($event).target.value)"
  (click)="click$.next($any($event).target.value)"
  #instance="ngbTypeahead"
/>
  • Related