angular-magic / ngx-gp-autocomplete

16 stars 4 forks source link

Can't change country dynamically #2

Closed aceleghin closed 1 year ago

aceleghin commented 1 year ago

I am trying to use your component instead of the original because I need to change the country in the options dynamically, but it seems not working.

<input #placesAutocomplete="ngx-places" (onAddressChange)="handleAddressChange($event)" formControlName="address" [options]="googlePlacesOptions" ngx-gp-autocomplete/>

I try to use your service ngxGpAutocompleteService.setOptions({ componentRestrictions: {country: this.country} })

And I try to change googlePlacesOptions like googlePlacesOptions={ // componentRestrictions: {country: this.country} }

But it seems not working.

dancornilov commented 1 year ago

Hey, sorry for late response.

I have encountered a similar use case wherein the autocomplete feature should provide related data based on the user's selected country. If I understand correctly, it is not possible to dynamically change the options of the autocomplete component at runtime. To overcome this limitation, I have implemented a workaround.

My use case:

https://github.com/angular-magic/ngx-gp-autocomplete/assets/24212761/e72e1a0f-65cc-4012-9edd-847dc81cd5cd

// HTML
<input
              #placeRef="ngx-places"
              (blur)="checkGeolocation()"
              (focus)="setAutocompleteCountry()"
              [formControl]="autocompleteControl"
              ngx-gp-autocomplete
              placeholder="ex. Strada Romană 134"
            />
// TS
export class MyComponent {
countryControl: FormControl = new FormControl(); // Value should be country code (ex: RO, FR, DE etc)
autocompleteControl: FormControl = new FormControl();
@ViewChild('placeRef') placeRef: NgxGpAutocompleteDirective;

checkGeolocation(): void {
    this.setAutocompleteCountry(this.countryControl.value);
  }

  setAutocompleteCountry(): void {
    this.placeRef.options = { componentRestrictions: { country: [this.countryControl.value] }, types: ['geocode'] };
    this.placeRef.reset();
  }
}