Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOninit variable is not binding in html angular 4

working on google map, able to display the map, I want to display the current location but its not displaying

     export class AppComponent {
      title = '';

      ngOnInit() {
    if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function (p) {
              var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);

              console.log(p.coords.latitude);
              console.log(p.coords.longitude);

              var geocoder = new google.maps.Geocoder();

             if (geocoder) {
            geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             console.log(results[0].formatted_address);
                 this.title = results[0].formatted_address;
                 console.log(this.title);
                 }
           else {
            console.log("Geocoding failed: " + status);
           }
        });
      }
    });
      } else {
          alert('Geo Location feature is not supported in this browser.');
      }

}

Here "this.title", i am getting the current location

HTML code

<h1> The Title is: {{title}}</h1>

in Console i am able to see the title value , why it is not binding in html?

like image 211
Vishnu Avatar asked Aug 01 '26 23:08

Vishnu


1 Answers

You are using the variable title declared in the scope of AppComponent class, inside the scope of the callback function inside geocode. You must access title with with its' original scope.

The trick is to store this into a variable, which in this case is the scope of AppComponent

export class AppComponent {
    title = '';
    var self = this;
    ......
}

And then use it inside any callback functions. Here in your case, it is the callback function inside geocode call

geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
   if (status == google.maps.GeocoderStatus.OK) {
       console.log(results[0].formatted_address);
       self.title = results[0].formatted_address; //Here we are using self, as the original context of title
       console.log(this.title);
   }
   else {
       console.log("Geocoding failed: " + status);
   }
});

Answer is also provided here in another question this-becomes-null

like image 197
Sandip Ghosh Avatar answered Aug 03 '26 16:08

Sandip Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!