从“自动完成”下拉选项中选择“材质自动完成角停止Api调用”

时间:2018-08-25 09:19:53

标签: javascript angular angular-material

我正在使用“材质角自动完成下拉菜单”功能在下拉菜单中填充位置预测。我正在使用onChange的材质从我创建的服务中调用api。我的问题是,当我从选择框中选择预测时,会再次向节点服务器触发api调用,因为再次触发了onChange。因此,当从下拉列表中选择一个选项时,我想停止对服务的Api调用。 这是模板的代码!

    <mat-form-field>
       <input matInput type="text" name="location" placeholder="Search By Location" aria-label="Location" [matAutocomplete]="auto" formControlName="location">
       <mat-autocomplete #auto="matAutocomplete" [displayWith]="location">
         <mat-option *ngFor="let places of predictions" (optionSelected)="predictionSelected($event)" [value]="places.description">
           <span>{{places.description}}</span>
         </mat-option>
       </mat-autocomplete>
   <mat-form-field>

在我的component.ts文件中,我编写了一个函数,该函数将调用我的Google Maps服务,并获取我对onChange的预测。我创建了一个事件函数,它是(optionSelected),当从下拉列表中选择值时将触发该事件。

predictionFilled = false;
ngOnInit() {
    this.customForm.get('location').valueChanges.subscribe(
      (value) => this.onChangeLocation(value)
    );
  }

  onChangeLocation(location) {
    if ( this.predictionFilled ) {
      return;
    }
    this.googleMapsService.suggestPlaces(location);
    this.placesPredictions = this.googleMapsService.getPredictionsUpdateListener().subscribe((predictions: Places[]) => {
      console.log(predictions);
      this.predictions = predictions;
    });
  }

  predictionSelected(event: any) {
    this.predictionFilled = true;
  }

问题在于,当我单击dropDown中的选项时,在valueChanges事件之后将触发事件(optionSelected)。从技术上讲,事件optionSelected应该在onChange之前触发,但我不明白为什么在optionSelected事件之前触发了valueChanges事件。

1 个答案:

答案 0 :(得分:0)

event中的predictionSelection()毫无用处。

您可以简单地在formControl valueChanges事件中编写该行,并将(optionSelected)="predictionSelected($event)"从注册它的mat element中删除。同样不需要predictionSelected(event : any)方法。

要停止调用api调用,您可以检查输入的值是否在predictions数组中,然后做出决定。

this.customForm.get('location').valueChanges.subscribe(
      (value) => {
           if (this.predictions.findIndex(value) > -1) {
                  this.predictionFilled = true; // value exists, then do not make api call
           }
           else {
                this.predictionFilled = false; // make api call
           }
           this.onChangeLocation(value);
      }
 );
相关问题