I am building an autocomplete component for address search with google maps service, for which I am using Angular 9. My component works, but I NEED TO CAPTURE THE VALUE OF THE INPUT WHEN THERE ARE NO SEARCHES AVAILABLE USING THE BLUR EVENT OR WHEN THE INPUT LOSE FOCUS.
Currently the component detects when I select an address, but I need to make it also detect the text I type when it does not find anything.
my html:
JavaScript
x
2
1
<input #search class="form-control" [formControl]="myAddress" type="text" placeholder="Enter a location">
2
My ts:
JavaScript
1
43
43
1
export class AddressComponent implements OnInit {
2
3
@Output() onSelectAddress = new EventEmitter<CustomAddressModel>();
4
5
myAddress = new FormControl('');
6
selectedAddress: PlaceResult;
7
8
@ViewChild('search')
9
searchElementRef: ElementRef;
10
11
constructor(
12
private _mapsAPILoader: MapsAPILoader,
13
private ngZone: NgZone,
14
) { }
15
16
ngOnInit(): void {
17
18
this._mapsAPILoader.load().then(() => {
19
20
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
21
autocomplete.addListener("place_changed", () => {
22
this.ngZone.run(() => {
23
24
this.selectedAddress = autocomplete.getPlace();
25
26
if (!this.selectedAddress.geometry) {
27
return;
28
}
29
30
const result = {
31
lat: this.selectedAddress.geometry.location.lat(),
32
long: this.selectedAddress.geometry.location.lng(),
33
strAddress: this.selectedAddress.formatted_address
34
} as CustomAddressModel;
35
36
this.onSelectAddress.emit(result);
37
38
});
39
});
40
});
41
}
42
}
43
Any idea?
Advertisement
Answer
usually you need to subscribe to the value changes of the input control.
JavaScript
1
24
24
1
ngOnInit() {
2
this.formchanges();
3
}
4
5
6
formchanges()
7
{
8
this.yourform.controls['myAddress'].valueChanges.pipe(
9
debounceTime(500),
10
finalize(() => {
11
12
})).subscribe(x => {
13
var address = safeTrim(this.yourform.get('myAddress').value);
14
15
this.getAddress(address);
16
}
17
});
18
}
19
20
getAddress()
21
{
22
//your call to the google maps api goes here
23
}
24
I am not sure , I was able to answer to your question or not.