【发布时间】:2019-01-31 14:27:40
【问题描述】:
我正在使用 Material Angular 自动完成下拉功能在我的下拉列表中填充位置预测。我正在使用材料的 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 中,我编写了一个函数,该函数将调用我的谷歌地图服务并获取我的 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;
}
问题是,当我从下拉菜单中单击选项时,事件 (optionSelected) 在 valueChanges 事件之后触发。从技术上讲,事件 optionSelected 应该在 onChange 之前触发,但我不明白为什么事件 valueChanges 在 optionSelected 事件之前触发。
【问题讨论】:
-
伙计们,你也可以给我一些其他的实现方法!!
-
为什么不从
form valueChanges事件中调用predictionSelected()?这样你就不需要注册(optionSelected)事件了。 -
我该怎么做?你能帮我写一些代码吗?
标签: javascript angular angular-material