Niko Gamulin
Niko Gamulin

Reputation: 66565

Angular binding issue - the paragraph does not update

After receiving the response from the external API, I want to display the value. The HTML looks as follows:

<section class="signup-form">
    <form fxLayout="column" fxLayoutAlign="center center" #f="ngForm" (ngSubmit)=onSubmit(f)>
        <mat-form-field>
            <input type="text" matInput placeholder="Label" ngModel name="label" required>
        </mat-form-field>
        <mat-form-field>
            <input type="text" matInput placeholder="Address" ngModel name="address" required>
        </mat-form-field>
        <div id="btnLocate" fxFlex fxLayout fxLayoutAlign="flex-end">
            <button type="submit" mat-raised-button color="primary">Locate...</button>
        </div>
        <div id="mapContainer" fxFlex fxLayout fxLayoutAlign="center">
            <p>{{ locatedAddress }}</p>
        </div>
        </div>
    </form>
</section>

and the following is the definition of the component:

export class DepotComponent implements OnInit {

  locatedAddress: string = null;

  constructor(private googleApiService: GoogleApiService) { 
  }

  ngOnInit(): void {
  }

  onLocateAddress(form: NgForm) {
    console.log(form.value.address);
    this.googleApiService.getLocation(form.value.address)
        .subscribe(
            (response: any) => {
              if (response){
                if(response.status === "OK"){
                  const firstMatch = response.results[0];
                  if (firstMatch.hasOwnProperty('partial_match') && firstMatch.partial_match) {
                    console.log('Address not found!')
                  }
                  this.locatedAddress = firstMatch.formatted_address;
                  console.log(this.locatedAddress);
                }
              }
            },
            (error) => console.log(error)
        );
  }

When the data is retrieved from the API (address), the value in the form is not changed. Does anyone know how to fix the issue?

Upvotes: 0

Views: 41

Answers (1)

Indraneel Pole
Indraneel Pole

Reputation: 299

First of all in your html you have onSubmit method, but in typescript I see onLocateAddress(), I am assuming that is just a mistake while posting the question. Second of all, Do you mean, it is not updating on

<p>{{ locatedAddress }}</p>

Or in your form inputs?

locatedAddress should be updated. Form inputs are probably not updating because you are not binding the returned result to the values that are bound by ngModel in your form. You are passing the value to locatedAddress object which is not bound to your form inputs

Upvotes: 1

Related Questions