在Angular 4中重置表单控件时始终调用服务API

时间:2018-10-08 12:01:02

标签: javascript angular angular-reactive-forms valuechangelistener

我下面有一个组件,该组件基本上在ngOnInit中调用外部API服务-这会在this.items中返回一组gif。

我具有功能applyGif-用户单击图像后它将调用此功能并重置表单searchTerm,问题是每次我调用resetSearchBox来清除文本输入框时它运行valueChanges事件,并再次以字符串值'null'执行gifpickerService.search-我不希望它没有值就调用它-我在做什么错? / p>

我想重置表单,但不调用search()中的ngOnInit-怎么了?

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组件* /

<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>

1 个答案:

答案 0 :(得分:1)

重置表单控件时,该值会更改,从而触发valueChanges。您可以使用emitEvent: false,这意味着它不会触发valueChanges

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

文档:https://angular.io/api/forms/FormControl#reset