Angular2 form control value.

I am currently trying to show a simple loader in the search bar while searching. I planned to set the variable in the subscribe valueChanges on the valueChanges observed from my form control to the value "load" and set it to an empty string in the full callback. However, a full callback is never called.

I also tried to add the callback finally to the observable, but it was also never called.

My code is:

 searchBox: Control = new Control(); loadingClass: string = ""; constructor() { this.searchBox.valueChanges .debounceTime(400) .distinctUntilChanged() .subscribe((text: string) => { this.imageSearch = text; this.loadingClass = "loading"; }, (err: Error) => { console.log(err); }, () => { this.loadingClass = ""; console.log("test"); }); } 
+5
source share
3 answers

I realized that I was trying to make a mistake. Instead, I realized that I have a debounceTime in my observable, so I logged a keyup event on my input control and set the value of loadingClass to "loading" , and in my subscription I set the value back to an empty line.

+1
source

This is normal since the observable never ends. valueChanges allows valueChanges to get the value from the search field. In fact, you want to be notified when a search action is completed.

So, I would try something similar, assuming that searchImage really does the search and returns the observable:

 constructor() { this.searchBox.valueChanges .debounceTime(400) .distinctUntilChanged() .flatMap((text:string) => { // <------- this.loadingClass = "loading"; return this.searchImage(text); }) .subscribe((searchResult) => { this.imageSearch = searchResult; this.loadingClass = ""; // <---- }, (err: Error) => { console.log(err); }); } 

See this article for using the flatMap operator:

+5
source

Hope this can lead some people to a better understanding of Angular2 forms. Angular has two different approaches to building forms (Reactive and Template form). Without knowing this, you may encounter confusing applications.

valuesChages is a property of the NgModel directive, and the FormControl class (remember this).

Reactive approaches use ReactiveFormsModule import (Your.module.ts):

 import {ReactiveFormsModule} from '@angular/forms'; @NgModule({ ... imports: [ ... ReactiveFormsModule, ... ], ... }) 

This way you can use the [(formControl)] property for your form controls (template.component.html).

 <input type="text" class="form-control" id="searchBox" required [(formControl)]="searchBox"/> 

Template Approach (your .module.ts):

 import {FormsModule} from '@angular/forms'; @NgModule({ ... imports: [ ... FormsModule, ... ], ... }) 

This object has its own form control properties, ngModel (your.template.ts):

 <input type="text" class="form-control" id="searchBox" required [(ngModel)]="searchBox"/> 
0
source

All Articles