How to get city name from ion-input field in ionic 3? - ionic-framework

Here I want to have only city name how simply I can get, I followed some blogs but kind of confused.
my html
<ion-input type="text" [(ngModel)]="default.city"></ion-input>
I am expecting something like
this.cityName = somefunction(inputText) {
...
return city;
}
I am looking for some ionic cordova plugin to autocomplete the typed location and list down the possible location and select one of them.

Depending on when you wish to show you autosearch results you can bind it to an event
<ion-input type="text" [(ngModel)]="default.city" (ionBlur)="someFunction()"></ion-input>
If you wish the autosearch results to come after he clicks out of the input box
you could use
(ionChange)="someFunction()" or (input)="someFunction()"
also if you need to
For Reverse geocoding you could use the geocoder plugin
https://github.com/sebastianbaar/cordova-plugin-nativegeocoder plugin
somefunction(inputText) {
this.nativeGeocoder.forwardGeocode('Berlin', options)
.then((coordinates: NativeGeocoderForwardResult[]) => {
this.autosearchresult = coordinates[0] // If you want one
})
.catch((error: any) => console.log(error));
}
and display it on the somwhere in the dom
<div (click)="completeauto()" *ngIf="showAutosearch">{{autosearchresult}}</div>
Keep in mind that you will also need some method to remove the search results and set the searchbar to the clicked value. If the user clicks on it.
Additionally if you have a Google Cloud Account you can activate the Google Places API which is more Robust than the Ionic Native version but you would require a credit card enabled account for it.
MapBox API also provides geocoding but I am not all that familiar with it.

If you have an Array of Object City cities, you can filter it by the name of the city in the following way
searchCityByName(searchText: any) {
const length = searchText.length;
console.log('filtering');
console.log(length);
if (length > 0) {
this.cities= this.cities.filter(city=> {
return city.name.toLowerCase().indexOf(searchText.toLowerCase()) >= 0;
});
}
}

Related

Accordion dropdown filtering through ion search bar

Hi I just created the ionic accordion dropdowns by following a tutorial blog link which used widgets for creating an accordion dropdowns, Below is the link of that blog.
http://masteringionic.com/blog/2019-01-27-creating-a-simple-accordion-widget-in-ionic-4/
updated: here is the my project demo link https://stackblitz.com/github/dSaif/search-accordion
Everything is working perfect, but i want to add Ion-searchbar at the top of the accordions sothat the dropdowns gets filter by inputing text.
please assist me how can i do that. Thank you.
You are going to have to create a variable in your homepage to store your filtered results. Then you need to have a filter function that will take the input from the search bar and filter your master list. Keep in mind you should not set the new variable to the master list, this could cause issues due to object referencing.
So you should have something like
in your html
<ion-searchbar placeholder="Search a name." [(ngModel)]="searchValue" (ionChange)="filterList()"></ion-searchbar>
In your ts file
searchValue: string = '';
filteredList: Array<{ name: string, description: string, image: string }> = this.technologies;
// function called in the html whenever you change the ion searchbar value
private filterList(){
//Make a variable so as to avoid any flashing on the screen if you set it to an empty array
const localFilteredList = []
this.technologies.forEach(currentItem => {
//here goes your search criteria, in the if statement
if(currentItem.name && currentItem.name.toLowerCase().includes(this.searchValue.toLowerCase())) {
localFilteredList.push(currentItem);
}
});
//finally set the global filter list to your newly filtered list
this.filteredList = localFilteredList;
}
You also need to make sure to reference the filterList variable instead of the current one you are referencing.

STOP Google Autofill/AutoComplete from ruining my form, Disable autofill on form

I have a form with an input field:
<input id="postalCode" placeholder="Postal Code* (A0A 0A0)" autocomplete="off">
I was using my own custom autocomplete here which google autofill COVERS and ruins the validation and user experience in my form.
I have tried changing the id to something random id="ASDf" and still google infers the field type by the validation or placeholder. I have tried the autocomplete="off" and "false". Neither do anything. On this page:
https://www.canadapost.ca/cpotools/apps/fpc/personal/findAnAddress?execution=e1s1
They have successfully disabled it somehow.
I have tried everything from this page:
Disabling Chrome Autofill
And nothing works.
Ok this worked for me:
role="presentation" autocomplete="nope"
tested on Chrome Version 64.0.3282.186 (Official Build) (64-bit).
I had to add both of those to each input in question. I also added to the form tag. For this specific version of Chrome the autofill is disabled. I am leaving this here because this is a real pain and ALL the up front solutions in other posts DO NOT work.
Solution : Replace 'Name' with your #id.
$('#Name').on('mouseup keyup', function () {
var val = $('#Name').val();
val = val.length;
if (val === 0) {
$('#Name').attr('autocomplete', 'on');
}
else {
$('#Name').attr('autocomplete', 'new-password');
}
}).on('mousedown keydown', function () {
var val = $('#Name').val();
var length = val.length;
if (!length) {
$('#Name').attr('autocomplete', 'new-password');
}
})

ionic2: How to display the selected result in the search bar when using ion searchbar with REST API?

I want to create a dropdown list with searchbar with the list containing data from a REST API.
Initially in the searchbar I created I could just select the item but couldn't display that in the searchbar. I want the selected item to be displayed in the searchbar.How can I display that selected item.
I need to display it because I'm building a cascading dropdown list where the input of the first list is served to the second list.
I'll be thankful if someone can provide me the code by putting mind that the data is being rendered from a REST API using POST method.This is my function which gets called in the html page.
userData is an array of type object since I need to get JSON data.I get an error saying property toLowerCase cannot exist on of the type Object.
loadusers(ev:any){
this.UserService.post('search/getusers',{}).subscribe(resp=>{
this.userData = resp.data;
console.log(this.userData);
},
err=>{console.log(err);},
()=>{});
let val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.userData = this.userData.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
This is the HTML file where I'm trying to display the data along with a searchabar.I also don't know what to include in the isChanged function.
<ion-searchbar [(ngModel)]="mySearchInput" (ionInput)="loadusers($event)"></ion-searchbar>
<ion-content >
<ion-list radio-group [(ngModel)]="selectedValue">
<ion-item class="border" *ngFor="let val of userData">
<ion-label>{{val.name}}</ion-label>
<ion-radio class="resolvedState" value="{{val.name}}" (ionSelect)="isChanged(val)"></ion-radio>
</ion-item>
</ion-list>
What is the best practise to create a searchbar with these features ?

Rxjs workflow for MongoDB Document References

I am developing an application on Ionic2/rc0. I got a ReplaySubject on a singlenton service that keeps the current user consistent across the whole app. It all works fine, I can subscribe to it and get a User object as easy as
this._user.Current.subscribe(user=>{ console.log(user)});
The User object looks like this
User {
confirmed:true
devices:["57f65werwe343bn8843f7h","7yr3243h5429hf2hjd"]
friends:["t245y53h65346htyh","356ytrer75dfhg43we56df"]
email:"francescoaferraro#gmail.com"
id:"57f6525e926bbc7615fc5c5c"
notification:false
password="$2a$04$.Fk/8eMj18ZrkfurbbdP4uT3yOs7Lb9db74GkNfgtABVY.ez2Q0I."
picture:"https://api.cescoferraro.xyz/kitty"
role:"master"
username:"cesco"
}
As you can see my backend is using MongoDB with One-to-Many Relationships with Document References as described here.
I have created a devices tab where I want to display all data about those user devices, but I need to call this._devices.info for each one of current.devices and concat the result back to TrueDevices
#Component({
template: `
<ion-header>
<ion-navbar>
<ion-title>Tabs</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<h2>Device:list</h2>
<h2 *ngFor="let item of devices | async">{{item}}</h2>
<button ion-button (click)="readDevice()">Read Random Device</button>
</ion-content>
`
})
export class DeviceComponent {
devices: Observable<string[]>;
TrueDevices: Observable<Device[]>;
constructor(public _user: UserService, public _device: DeviceService) {
this._user.Current.subscribe(user=>{ this.devices = Observable.of(user.devices)});
// Get current User
// call this._devices.info for each one of current.devices
// concat the result back to TrueDevices
this._user.Current
.subscribe((result) => { console.log(result) });
}
readDevice(){
console.log(this.devices);
this._device.info(this.devices.value[0]).subscribe(data=>console.log(data))
}
}
I will need to repeat the same procedure to the friends tab and so on. I am pretty sure there are a couple operators that would do the magic, but I am fairly new to rxjs and not familiar with all of them. Whats the right approach?
this._user.Current
.switchMap(user => Observable.from(user.devices)) // after this line, you have an Observable<string>
.mergeMap(device => this._device.info(device)) // each device will be mapped to another observable(or stream), and all the streams will be merged together
.toArray() // wait for all the streams to complete and reduce all the results into an array.
.subscribe(array => console.log(array));
or go to the gitter room:
https://gitter.im/Reactive-Extensions/RxJS

Capturing changes to model using angular-google-places-autocomplete

I'm using angular-google-places-autocomplete (https://github.com/kuhnza/angular-google-places-autocomplete) with Ionic but having problems capturing the selected option when using this directive.
I have the directive set up like this:
<!-- template -->
<input type="text" placeholder="Place search" g-places-autocomplete ng-model="locationSearchResult"/>
<h5>Result</h5>
<pre ng-bind="locationSearchResult | json"></pre>
My controller code is set up to watch for changes to the locationSearchResult model, and if it does change to save the new location to local storage:
// Controller
$scope.locationSearchResult = {};
$scope.$watch('locationSearchResult', function(newVal, oldVal) {
if (angular.equals(newVal, oldVal)) { return; }
$scope.$storage.loc = newVal;
$state.go('new-page');
});
When using the autocomplete it seems to work as expected - I get a list of predictions, and selecting a prediction from the list of predictions updates the text input with the name of the selected place, and the JSON data for the selected place displays under the result heading. But, the change doesn't seem to be picked up by the $scope.$watch in the controller.
As a result, I can't seem to be able to capture the search result data and do anything with it - like add it to the user session.
Maybe I'm just going about it the wrong way (though I used the same approach with ngAutocomplete and it worked ok).
Use the event that gets emitted in your controller.
$scope.$on('g-places-autocomplete:select', function (event, param) {
console.log(event);
console.log(param);
});