Search code examples
angularformsgoogle-geocoderangular-google-maps

Data not being sent to FormGroup - Angular


I have a single field form, and the data is not being sent to my FormGroup. It is empty when I log it for some strange reason.

My TS file

  addressData: FormGroup;
  submitted = false;
  success = false;

  userLat: number;
  userLng: number;

  private geoCoder: google.maps.Geocoder;

  constructor(private maps: MapsAPILoader, private bulider: FormBuilder, private ref: ChangeDetectorRef) { }

  ngOnInit() {
    this.addressData = this.bulider.group({
      address: ["", Validators.required],
    });
    console.log("Init data: " + this.addressData.controls['address'].value);

    this.maps.load().then(() => {
      this.geoCoder = new google.maps.Geocoder();
    });
  }

  getAddress() {    
    this.submitted = true;

    // I commented this out to see if the geocoder works
    // if (this.addressData.invalid) {
    //   console.error("Invalid address! Address: " + this.addressData.value);
    //   return;
    // }

    this.geoCoder.geocode({ 'address': this.addressData.controls['address'].value }, (results, status) => {
      if (status === google.maps.GeocoderStatus.OK) {
        this.userLat = results[0].geometry.location.lat();
        this.userLng = results[0].geometry.location.lng();
        this.ref.detectChanges();
        this.success = true;
      } else {
        // The address is empty, therefore gives me invalid_request
        alert('Geocode was not successful for the following reason: ' + status + " and Address: " + this.addressData.controls['address'].value);
      }
    });
    this.submitted = false;
  }
}

HTML

<div>
    <form [formGroup]="addressData" (ngSubmit)="getAddress()">
      <input class="addressBar" type="text" placeholder="Address" maxlength="30" autofocus>
      <br><br><button class="searchBtn" type="submit">Search</button>
    </form>
  </div>

I know you can use #address in the HTML, and pass it to the method, getAddress(), but I want to do it this way because I am going to use error messages for user feedback.

Expected:

I want the address to be validated as required and be used in the geocoder.

Actual:

The FormGroup is empty and is always invalid (no matter what you type in), and therefore cannot be used in the geocoder.


Solution

  • You need to add formControlName

      <input type="text" formControlName="address">
    

    Quote from Step 2: Associating the FormGroup model and view:

    Note that just as a form group contains a group of controls, the profile form FormGroup is bound to the form element with the FormGroup directive, creating a communication layer between the model and the form containing the inputs. The formControlName input provided by the FormControlName directive binds each individual input to the form control defined in FormGroup. The form controls communicate with their respective elements.