Ion-input not working inside a modal View ionic 2 (android)


#1

Hi,

I am using segment which has 2 buttons with FAB. On click of FAB modal view opens which is same for both segment buttons. unfortunately on first segment modal works fine but the same modal not working properly on second button click on segment.

here is the code:

segment.html

Extentia Cafe Outlets
Cafelist Cafelocations
<ion-list inset *ngSwitchCase="'cafelist'">
  <ion-item *ngFor="let item of items">
    {{ item.name }}
    <h2>{{item.location}}</h2>
    <h3>{{item.description}}</h3>
  </ion-item>
</ion-list>

<div #map id="map" *ngSwitchCase="'cafelocations'">

</div>

segment.ts

import { Component, ViewChild, ElementRef, OnInit } from ‘@angular/core’;
import { IonicPage, NavController, Platform, NavParams, AlertController, ModalController, ToastController, LoadingController } from ‘ionic-angular’;
import { CafeService } from ‘…/services/cafe.service’;
import { URL } from ‘…/constants/constants’;
import { Login } from ‘…/login/login’;
import { ModalPage } from ‘…/modal/modalpage’;
import { Geolocation } from ‘@ionic-native/geolocation’;
import { GoogleMap, GoogleMapsEvent, LatLng, MarkerOptions, Marker, CameraPosition } from ‘@ionic-native/google-maps’;
import { HttpService } from ‘…/services/http.service’;

declare var google;

let Title: string;
let Msg: string;
let btn: string;
let user_id: string;
let mapMarker: any;

@Component({
selector: ‘page-segment’,
templateUrl: ‘segment.html’,
providers: [CafeService, HttpService]
})
export class SegmentPage implements OnInit {
defaultZoom: any;
onLocationSelected: any;
myLong: number;
myLat: number;
address;
locationCoordinates: any;
map: any;
fromValue: string;
toValue: string;
public items: any;
cat: string = “cafelist”;
constructor(public navCtrl: NavController, public loadingCtrl: LoadingController, public httpService: HttpService, public toastCtrl: ToastController, public geolocation: Geolocation, public navParams: NavParams, public cafeService: CafeService, public alertCtrl: AlertController, public modalCtrl: ModalController) {
this.fromValue = ‘’;
this.toValue = ‘’;
{
this.address = {
place: ‘’
};
}
}

presentToast() {
let toast = this.toastCtrl.create({
message: ‘Extentia Cafe Outlet Added Successfully’,
duration: 2000,
position: ‘bottom’
});
toast.present();
}
presentModal() {

let that = this;
let modal = this.modalCtrl.create(ModalPage,{mapAddress:this.locationCoordinates});
modal.present();

modal.onDidDismiss(data => {
  if (data == "success") {
    that.presentToast();
    that.postRequest();
  }
  else if (data != undefined) {

    console.log("data " + data);
    let url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + data + "&key=AIzaSyARBYHwwK5uPoNuS2iN3UOg8fQGRgHLz78";

    console.log(this.address.place);
    this.httpService.post("", url).subscribe(data => {

      console.log(data);
      console.log(data.json);
      console.log(data.json.results[0].formatted_address);
      let ionic: LatLng = new LatLng(data.json.results[0].geometry.location.lat, data.json.results[0].geometry.location.lng);
      console.log(data.json.results[0].geometry.location.lat);
      console.log(data.json.results[0].geometry.location.lng);
      let position: CameraPosition = {
        target: ionic,
        zoom: 18,
        tilt: 30
      };
      this.map.moveCamera(position);
      let markerOptions: MarkerOptions = {
        position: ionic,
        title: 'Ionic',
        draggable: true
      };
      this.map.addMarker(markerOptions)
        .then(
        (marker: Marker) => {
          mapMarker = marker;
          console.log("marker");
          marker.showInfoWindow();
          marker.on(GoogleMapsEvent.MARKER_DRAG_END)
            .subscribe(() => {
              marker.getPosition()
                .then((position: LatLng) => {
                  this.locationCoordinates = position;
                  console.log(this.locationCoordinates.lat);
                  console.log(this.locationCoordinates.lng);
                  console.log('Marker was moved to the following position: ', position);
                });
            });
        }
        );

    }, error => {
      alert("error" + error);
      console.log(error);

    });
  }

  else {
    console.log(data);
  }


});

}
updatePage(cat) {
if (cat === ‘cafelocations’) {
this.loadMap();
}
}

ionViewDidLoad() {
console.log(‘ionViewDidLoad SegmentPage’);

}
ionViewDidEnter() {
this.postRequest();
}

postRequest() {

let loading = this.loadingCtrl.create({
  content: 'Please wait...'
});
loading.present();

console.log(localStorage.getItem("userid"));
let postParams = {
  userid: user_id
}

if ("userid" in localStorage) {

  user_id = localStorage.getItem("userid");
  console.log("reached");

  this.cafeService.getAllCafeList(postParams, URL.GET_CAFELIST_URL).subscribe(data => {
    loading.dismiss();
    console.log(data);

    console.log(data.json);
    console.log(data.json.cafeList);


    if (data.json.status == "SUCCESS") {


      this.items = data.json.cafeList;

    }

  }, error => {
    loading.dismiss();
    alert("error" + error);
    console.log(error);

  });


}

else {

  loading.dismiss();
  console.log("else part");
  this.navCtrl.push(Login);
}

}

showAlert() {
let alert = this.alertCtrl.create({
title: Title,
subTitle: Msg,
buttons: [btn]
});
alert.present();
}

addNewCafe(): void {
if (mapMarker != undefined) {
mapMarker.remove();
}
this.presentModal();

}

loadMap() {

this.geolocation.getCurrentPosition().then((resp) => {

  
  this.myLat = resp.coords.latitude;
  this.myLong = resp.coords.longitude;
  let location = new LatLng(this.myLat, this.myLong);

  this.map = new GoogleMap('map', {
    'backgroundColor': 'white',
    'controls': {
      'compass': true,
      'myLocationButton': true,
      'indoorPicker': true,
      'zoom': true
    },
    'gestures': {
      'scroll': true,
      'tilt': true,
      'rotate': true,
      'zoom': true
    },
    'camera': {
      'latLng': location,
      'tilt': 30,
      'zoom': 15,
      'bearing': 50
    }
  });

  this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
    console.log('Map is ready!');
  });

}).catch((error) => {
  console.log('Error getting location', error);
});

}

ngOnInit(): void {

}

ngAfterViewInit(): void {
//this.loadMap();

}

loading() {

let input_from = (<HTMLInputElement>document.getElementById('journey_from'));
let input_to = (<HTMLInputElement>document.getElementById('journey_to'));


let options = {
  types: [],
  componentRestrictions: { country: "IND" }
};


let autocomplete1 = new google.maps.places.Autocomplete(input_from, options);



let self = this;


google.maps.event.addListener(autocomplete1, 'place_changed', function () {

  let place = autocomplete1.getPlace();
  let geometry = place.geometry;
  if ((geometry) !== undefined) {

    console.log(place.name);

    console.log(geometry.location.lng());

    console.log(geometry.location.lat());

  }
});

}

}

modalPage.html

Enter address {{ item }}

<button class=“modal” style=“margin-top:20px” [disabled]="!userInputData.cafeName || !userInputData.location || !userInputData.description" (click)="addCafe()"
ion-button block color=“dark” outline>Add Cafe

modalPage.ts

import { Component, OnInit, NgZone } from ‘@angular/core’;
import { NavController, NavParams, ViewController } from ‘ionic-angular’;
import { CafeService } from ‘…/services/cafe.service’;
import { Http, Headers, RequestOptions } from ‘@angular/http’;
import ‘rxjs/add/operator/map’;
import { URL } from ‘…/constants/constants’;
import { UserInputData } from ‘…/userinputdata/UserInputData’;
import { HttpService } from ‘…/services/http.service’;

declare var google;

@Component({
selector: ‘page-modalpage’,
templateUrl: ‘modalpage.html’,
providers: [CafeService, HttpService]
})

export class ModalPage implements OnInit {

autocompleteItems;
autocomplete;
userInputData: UserInputData = {};
coordinates:any;
constructor(public params: NavParams, private viewCtrl: ViewController, public http: Http, private cafeService: CafeService, private zone: NgZone, public httpService: HttpService) {

console.log(this.params.get('mapAddress'));
this.coordinates = this.params.get('mapAddress');
// if (this.coordinates != undefined) {
//   console.log("location coordinates " + coordinates.lat);
//   this.userInputData.location = {
//     name: '',
//     lat: coordinates.lat,
//     lng: coordinates.lng
//   };

//   console.log("location coordinates set " + this.userInputData.location);
// }
this.autocompleteItems = [];
this.autocomplete = {
  query: ''
};

}

dismiss(data) {
console.log("data " + data);
this.viewCtrl.dismiss(data);
//google.maps.event.clearInstanceListeners(document.getElementById(‘journey_from’));
}

addCafe(): void {

if (this.coordinates != undefined) {
  console.log("location coordinates " + this.coordinates.lat);
  this.userInputData.location = {
    name: this.userInputData.cafeName,
    lat: this.coordinates.lat,
    lng: this.coordinates.lng
  };

  console.log("location coordinates set " + this.userInputData.location);
}
// google.maps.event.clearInstanceListeners(document.getElementById('journey_from'));
let postParams = {
  name: this.userInputData.cafeName,
  location: this.userInputData.location,
  description: this.userInputData.description,
  user_ref_id: localStorage.getItem("userid")
}

console.log(postParams.name);
console.log(postParams.location);
console.log(postParams.description);
console.log(postParams.user_ref_id);

this.cafeService.addNewCafe(postParams, URL.ADD_CAFE_URL).subscribe(data => {

  console.log(data);


  if (data.json.status == "SUCCESS") {

    console.log("added successfully");

    this.viewCtrl.dismiss("success");

  }

}, error => {
  alert("error" + error);
  console.log(error);

});

}

loading() {
//get the two fields
let input_from = (document.getElementById(‘journey_from’));
console.log(input_from);
//let input_to = (document.getElementById(‘journey_to’));

// set the options
let options = {
  types: [],
  componentRestrictions: { country: "IND" }
};

// create the two autocompletes on the from and to fields
let autocomplete1 = new google.maps.places.Autocomplete(input_from, options);
//let autocomplete2 = new google.maps.places.Autocomplete(input_to, options);

// we need to save a reference to this as we lose it in the callbacks
let self = this;

// add the first listener
google.maps.event.addListener(autocomplete1, 'place_changed', function () {

  let place = autocomplete1.getPlace();
  let geometry = place.geometry;
  if ((geometry) !== undefined) {

    console.log(place.name);

    console.log(geometry.location.lng());

    console.log(geometry.location.lat());

  }
});

}
chooseItem(item: any) {

console.log("item " + item);
this.userInputData.location = item;
this.viewCtrl.dismiss(item);

}

updateSearch() {
if (this.autocomplete.query == ‘’) {
this.autocompleteItems = [];
return;
}
let me = this;
console.log(“query " + this.autocomplete.query);
this.autocompleteItems = [];
//let predictions: any = [];
let url: string = “https://maps.googleapis.com/maps/api/place/autocomplete/json?input=” + this.autocomplete.query + “&types=establishment&components=country:ind&location=18.5204,73.8567&key=AIzaSyARBYHwwK5uPoNuS2iN3UOg8fQGRgHLz78”;
this.httpService.post(”", url).subscribe(data => {
//alert("data " + data);
// console.log(data[’_body’]);
// var stat = data[’_body’];
// stat = JSON.parse(data[’_body’]);
console.log(data);
console.log(data.json);
console.log(data.json.predictions[0].description);

  me.zone.run(function () {
    data.json.predictions.forEach(function (prediction) {
      me.autocompleteItems.push(prediction.description);
    });
  });

  if (data.json.status == "SUCCESS") {

    console.log("success");

  }

}, error => {
  alert("error" + error);
  console.log(error);

});

//  this.service.getPlacePredictions({ input: this.autocomplete.query, componentRestrictions: { country: 'IND' } }, function (predictions, status) {
//         if (status != google.maps.places.PlacesServiceStatus.OK) {
//             alert(status);
//             return;
//         }
//         me.autocompleteItems = [];
//   me.zone.run(function () {
//     predictions.forEach(function (prediction) {
//       me.autocompleteItems.push(prediction.description);
//     });
//   });
// });

}

ngOnInit(): void {

}

ngAfterViewInit(): void {

// let input_from = document.getElementById('journey_from').getElementsByTagName('input')[0];

// let options = {
//   types: [],
//   componentRestrictions: { country: "IND" }
// };


// let autocomplete1 = new google.maps.places.Autocomplete(input_from, options);

// let self = this;


// google.maps.event.addListener(autocomplete1, 'place_changed', function () {

//   let place = autocomplete1.getPlace();
//   let geometry = place.geometry;
//   if ((geometry) !== undefined) {

//     console.log(place.name);

//     console.log(geometry.location.lng());

//     console.log(geometry.location.lat());

//   }
// });

}

}


#2

The code works fine on browser only issue is observed on android. On android ion-input won’t work when i click to type inside the input.


#3

Your post is unreadable.

Please edit your post and use the </> button above the post input field to format your code or error message or wrap it in ``` (“code fences”) manually. This will make sure your text is readable and if it recognizes the programming language it also automatically adds code syntax highlighting. Thanks.