我有一个页面,用户可以在其中输入并从自动完成中选择一个地址。自动完成的来源来自于使用 valueChanges 事件调用的外部 API。
结果行为是基于用户输入的预测地址查找行为。这目前适用于这个单一的目的。
<mat-form-field>
<input matInput placeholder="Search Multi" aria-label="State" [matAutocomplete]="auto" [formControl]="searchMoviesCtrl" type="text">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngIf="isLoading" class="is-loading">Loading...</mat-option>
<ng-container *ngIf="!isLoading">
<mat-option *ngFor="let suggestion of filteredMovies" [value]="suggestion.text">
<span><b>{{suggestion.text}}</b></span>
</mat-option>
</ng-container>
</mat-autocomplete>
</mat-form-field>
<br>
<ng-container *ngIf="errorMsg; else elseTemplate">
{{errorMsg}}
</ng-container>
<ng-template #elseTemplate>
<h5>Selected Value: {{searchMoviesCtrl.value}}</h5>
</ng-template>
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { debounceTime, tap, switchMap, finalize } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
searchMoviesCtrl = new FormControl();
filteredMovies: any;
isLoading = false;
errorMsg: string;
constructor(private http: HttpClient)
{ }
ngOnInit() {
this.searchMoviesCtrl.valueChanges
.pipe(
debounceTime(500),
tap(() => {
this.errorMsg = "";
this.filteredMovies = [];
this.isLoading = true;
}),
switchMap(value => this.http.get("http://searchaddressapiurl?text=" + this.searchMoviesCtrl.value)
.pipe(
finalize(() => {
this.isLoading = false
}),
)
)
)
但是,我想允许用户添加额外的自动完成输入,这将在值更改时使用/调用相同的 API。
我该怎么做才能做到最好?
婷婷同学_
相关分类