goyote
goyote

Reputation: 573

How to debounce SearchBar in NativeScript Angular?

I want to debounce the search input:

export class SearchComponent implements OnInit {

    onTextChanged(args) {
        let searchBar = <SearchBar>args.object;

        if (searchBar.text) {
            this.updateResults(searchBar.text);
        } else {
            this.results = new ObservableArray();
        }
    }

    updateResults(q) {
        // hit api
    }
}


<SearchBar (textChange)="onTextChanged($event)"></SearchBar>

As is the backend will be hit on every keystroke.

Upvotes: 2

Views: 787

Answers (2)

FrontEnd-er
FrontEnd-er

Reputation: 663

Try to this for SearchBar in nativescript.

HTML:-

<SearchBar class="form-input search-barHead" [text]="searchPhrase" 
(loaded)="searchBarLoaded($event)"
  textFieldHintColor="#ffffff" textFieldBackgroundColor="#02637E" height="40" 
  hint="Search TCP" (clear)="onAllSearchClear($event)" (submit)="onAllSearchSubmit($event)"> 

Typescript:-

Public searchPhrase:any;

public searchBarLoaded(args) {
    let searchBar = <SearchBar>args.object;
    if (searchBar.android) {
        searchBar.android.clearFocus();
    }
}

public onAllSearchClear(args) {
    let searchBar = <SearchBar>args.object;
    let searchProduct = searchBar.text;
}

public onAllSearchSubmit(args) {
    let searchBar = <SearchBar>args.object;
    let searchProduct = searchBar.text;
}

Upvotes: 0

Manoj
Manoj

Reputation: 21908

Use the FromControl and add debounceTime operator at valueChanges subscription. Make sure you import the ReactiveFormsModule too.

HTML

<SearchBar [formControl]="searchControl" class="input"></SearchBar>

TS

this.subscription = this.searchControl.valueChanges
        .pipe(debounceTime(500))
        .subscribe((value) => {
            console.log(value);
        });

Playground Sample

Upvotes: 0

Related Questions