javascriptangularangular-reactive-formsvaluechangelistener

always calling the service API when resetting the form control in Angular 4


I have a component below that basically calls an external API service within ngOnInit - this returns an array of gifs in this.items.

I have the function applyGif - once a user clicks an image it calls this function and resets the Form searchTerm the problem is each time I call resetSearchBox to clear the text input box it runs the valueChanges event and executes the the gifpickerService.search again with a string value of 'null' - I do not want it to ever call this if it has no value - what am I doing wrong?

I want to reset the form but not call the search() within the ngOnInit - what am doing wrong?

export class GifpickerComponent implements OnInit {
   public searchTerm : FormControl = new FormControl();
   public items: any = [];

   @Output() gifSelected: EventEmitter<any> = new EventEmitter<any>();

   constructor(private gifpickerService: GifpickerService) {}

   ngOnInit() {
       this.searchTerm.valueChanges
          .debounceTime(1000)
          .subscribe(data => {
             this.gifpickerService.search(data).subscribe(response =>{
                 this.items = response;
           })

      })
   }

  applyGif(gif): any {
      let gifMedia = gif.media[0];
      this.gifSelected.emit(gifMedia);
      this.resetSearchBox();
  }

  toggleGifList(): void {
      this.items = [];
  }

  resetSearchBox(): void {
      this.searchTerm.reset();
  }
}

/* html component */

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let item of items" [value]="item" class="gif-list-item">
      <img [src]="item.media[0].tinygif.url" (click)="applyGif(item)" />
  </mat-option>
</mat-autocomplete>

Solution

  • When you are resetting the form control, the value changes and thus triggers the valueChanges. You can use emitEvent: false which means it will not trigger valueChanges:

    resetSearchBox(): void {
      this.searchTerm.reset(null, { emitEvent: false });
    }
    

    Docs: https://angular.io/api/forms/FormControl#reset