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:
<input #search class="form-control" [formControl]="myAddress" type="text" placeholder="Enter a location">
My ts:
export class AddressComponent implements OnInit {
@Output() onSelectAddress = new EventEmitter<CustomAddressModel>();
myAddress = new FormControl('');
selectedAddress: PlaceResult;
@ViewChild('search')
searchElementRef: ElementRef;
constructor(
private _mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
) { }
ngOnInit(): void {
this._mapsAPILoader.load().then(() => {
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
this.selectedAddress = autocomplete.getPlace();
if (!this.selectedAddress.geometry) {
return;
}
const result = {
lat: this.selectedAddress.geometry.location.lat(),
long: this.selectedAddress.geometry.location.lng(),
strAddress: this.selectedAddress.formatted_address
} as CustomAddressModel;
this.onSelectAddress.emit(result);
});
});
});
}
}
Any idea?
Advertisement
Answer
usually you need to subscribe to the value changes of the input control.
ngOnInit() {
this.formchanges();
}
formchanges()
{
this.yourform.controls['myAddress'].valueChanges.pipe(
debounceTime(500),
finalize(() => {
})).subscribe(x => {
var address = safeTrim(this.yourform.get('myAddress').value);
this.getAddress(address);
}
});
}
getAddress()
{
//your call to the google maps api goes here
}
I am not sure , I was able to answer to your question or not.