How to use autocomplete on search bar on Ionic 4? - autocomplete

I'm looking for some example but cannot see anyone googling it, just what i want is to hardcode 2 or 3 words, thank you so much. Do i have to look for on ionic 3? or in angular2 better?

In your html file:
<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
<ion-list *ngIf="isItemAvailable">
<ion-item *ngFor="let item of items">{{ item }}</ion-item>
</ion-list>
in your ts file:
// Declare the variable (in this case and initialize it with false)
isItemAvailable = false;
items = [];
initializeItems(){
this.items = ["Ram","gopi", "dravid"];
}
getItems(ev: any) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
const val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() !== '') {
this.isItemAvailable = true;
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
} else {
this.isItemAvailable = false;
}
}

Mohan Gopi's answer is complete, but in order to make use of the debounce attribute, you have to use the ionChange event instead of the ionInput event.
<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
...
...
That way the event will trigger after the user stops typing (after 500 milliseconds have passed since his last key press), instead of whenever a key is pressed.

Just wanted to share something I tried myself. I have implemented the autocomplete from Angulars material design (https://material.angular.io/components/autocomplete/overview)
But it did not look exactly as the rest of the ionic input components. I also tried the ion-searchbar but I did not like the search input, I wanted a normal ion-input So I did this:
html:
<ion-list>
<ion-item>
<ion-label position="floating">Supplier*</ion-label>
<ion-input (ionChange)="onSearchChange($event)" [(ngModel)]="supplier"></ion-input>
</ion-item>
<ion-item *ngIf="resultsAvailable">
<ion-list style="width: 100%; max-height: 200px; overflow-y: scroll;">
<ion-item *ngFor="let result of results" (click)="supplierSelected(result)" button>
<ion-label>{{result}}</ion-label>
</ion-item>
</ion-list>
</ion-item>
</ion-list>
in component.ts:
resultsAvailable: boolean = false;
results: string[] = [];
ignoreNextChange: boolean = false;
onSearchChange(event: any) {
const substring = event.target.value;
if (this.ignoreNextChange) {
this.ignoreNextChange = false;
return;
}
this.dataService.getStrings(substring).subscribe((result) => {
this.results = result;
if (this.results.length > 0) {
this.resultsAvailable = true;
} else {
this.resultsAvailable = false;
}
});
}
supplierSelected(selected: string) :void {
this.supplier = selected;
this.results = [];
this.resultsAvailable = false;
this.ignoreNextChange = true;
}
Granted the question was about ion-searchbar but maybe somebody out there also wants to use a normal ion-input like me. There is no clear icon but I can live with that, or just add one next to the ion-input. Could be that there is a way to turn the ion-searchbar into a normal ion-input style? Can't find it though in the docs.

Related

how to show the selected value in radio button as checked when opening the ion-lost again after selection in ionic

I have a field which opens a list having ion-radio.On selection of an option it shows the selected value as checked and when i open the list again, the checked value is not shown.
here is my code:
code to show the options in modal controller :
let modal = this.modalCtrl.create(ListComponent, { selectEmpType: type, selectValue: value, customiseColor: this.customiseColor , formMrType :formMrType, limitedRoleList : this.limitedRoleList, formType:this.formType,defaultOU1:this.defaultOus[0],defaultOU2:this.defaultOus[1],defaultOU3:this.defaultOus[2]});
modal.onDidDismiss(data => {
if (data.type == 'single') {
this.setEmpValue(data.data, name); //data.data is the value that is selected from the list
}
}
in listcomponent.html:
<div *ngIf= "formMrType =='employee'">
<ion-list radio-group [(ngModel)]="relationship">
<ion-item *ngFor="let option of inputDatas">
<ion-label>{{option.EMPFullName}}</ion-label>
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}"></ion-radio>
</ion-item>
</ion-list>
</div>
how to show the selected option as checked when opening the list for second time.
Preferably, you should be using ion-select for such functionality..
If you are using latest ionic versions ion-radio-group
But even in your case..you can try something like this...
<ion-radio [checked]="option.checked" value="{{option.EMPFullName}}" (ionBlur)="optionBlur(option)"></ion-radio>
optionBlur(option){
if(!option['checked']){
option['checked'] = true;
}
else{
option['checked'] = !option['checked']
}
}

Ionic 3 using ion-checkbox for only select one

How can I using checkbox for select one (just like radio), my code:
<div *ngFor="let address of addresses; let i = index;">
<ion-item>
<ion-checkbox id="cb_{{address.id}}" (ionChange)="selectedAddress(address.id,addresses,i)" checked="false"></ion-checkbox>
</ion-item>
</div>
in ts file:
selectedAddress(id,addresses,index){
for(let i=0; i<addresses.length; i++){
if(index != i){
document.getElementById("cb_"+addresses[i].id).checked = false;
}
}
}
but it is not working, anyone know how to achieve it? thanks a lot
Bind address.checked = false; kind thing when page is loading using for loop or using the API.
pass address object trough
selectedAddress(address,addresses,i) method.
in.ts
selectedAddress(address,addresses,i)
{
address.checked = !address.checked;
}

Infinite loop and dynamic content on slides [duplicate]

Hi I'm using ngFor to create an set of 3 slides while starting in the middle so I'm guaranteed to be able to slide to left or right on start.
When I slide right I can simple listen to the reachedEnd and push another slide to the array i'm looping.
but I have a problem with adding a slide to the beginning. If I do the same as above and use e.g. array.unshift() or spread to add an item to the beginning, the view think it's on position 0 and snaps the view to the new slide.
The code below would work but it animates the slide change back to index 1.
slide = [0,1,2] //example to loop
slideChanged(event) {
if(this.slides.isBeginning()){
this.slide = [this.slide[0]-1, ...this.slide];
this.slides.update();
this.slides.slideTo(1)
}
}
<ion-slides [initialSlide]="1" (ionSlideDidChange)="slideChanged($event)">
<ion-slide *ngFor="let item of slide">
<h1>Slide {{item}}</h1>
</ion-slide>
</ion-slides>
Any help is appreciated!
You can do that by using the ionSlideNextEnd and ionSlidePrevEnd events from the Slides. Please take a look at this working plunker
The view
<ion-header>
<ion-navbar>
<ion-title>Dynamic slides Demo</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-slides #slider (ionSlideNextEnd)="loadNext()" (ionSlidePrevEnd)="loadPrev()" [initialSlide]="1">
<ion-slide *ngFor="let n of numbers">
<h2>Current slide: {{n}}</h2>
</ion-slide>
</ion-slides>
</ion-content>
The component
#Component({...})
export class HomePage {
#ViewChild('slider') private slider: Slides;
numbers = [0,1,2];
firstLoad = true;
constructor() {}
loadPrev() {
console.log('Prev');
let newIndex = this.slider.getActiveIndex();
newIndex++;
this.numbers.unshift(this.numbers[0] - 1);
this.numbers.pop();
// Workaround to make it work: breaks the animation
this.slider.slideTo(newIndex, 0, false);
console.log(`New status: ${this.numbers}`);
}
loadNext() {
if(this.firstLoad) {
// Since the initial slide is 1, prevent the first
// movement to modify the slides
this.firstLoad = false;
return;
}
console.log('Next');
let newIndex = this.slider.getActiveIndex();
newIndex--;
this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
this.numbers.shift();
// Workaround to make it work: breaks the animation
this.slider.slideTo(newIndex, 0, false);
console.log(`New status: ${this.numbers}`);
}
}
For you who wonder why this not works on Ionic 4, just add little bit changes on typescript component
This code below works on IONIC 4 :
ionSlideNextEnd(){
if(this.firstLoad) {
// Since the initial slide is 1, prevent the first
// movement to modify the slides
this.firstLoad = false;
return;
}
console.log('Next');
this.daySlider.getActiveIndex().then(idx=>{
let newIndex=idx
console.log(newIndex)
newIndex--;
this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
this.numbers.shift();
// Workaround to make it work: breaks the animation
this.daySlider.slideTo(newIndex, 0, false);
console.log(`New status: ${this.numbers}`);
});
}
ionSlidePrevEnd(){
console.log('Prev');
this.daySlider.getActiveIndex().then(idx=>{
let newIndex=idx
console.log(newIndex)
newIndex++;
this.numbers.unshift(this.numbers[0] - 1);
this.numbers.pop();
// Workaround to make it work: breaks the animation
this.daySlider.slideTo(newIndex, 0, false);
console.log(`New status: ${this.numbers}`);
});
}
Or Much more simpler you can remove getter for Active Index, use below code for Ionic 4:
ionSlideNextEnd(){
if(this.firstLoad) {
this.firstLoad = false;
return;
}else{
this.numbers.push(this.numbers[this.numbers.length - 1] + 1);
this.numbers.shift();
// Workaround to make it work: breaks the animation
this.daySlider.slideTo(1,0,false);
this.monthViewData.selectedTime=new Date(this.monthViewData.selectedTime.setDate(this.monthViewData.selectedTime.getDate()+1));
this.eventSource = this.tmp_events.filter((item)=>{
if(item.startTime >= this.monthViewData.selectedTime.setHours(0,0,0,0) && item.endTime < this.monthViewData.selectedTime.getTime()){
return item;
}
});
}
}
ionSlidePrevEnd(){
this.numbers.unshift(this.numbers[0] - 1);
this.numbers.pop();
this.daySlider.slideTo(1,0,false);
this.monthViewData.selectedTime=new Date(this.monthViewData.selectedTime.setDate(this.monthViewData.selectedTime.getDate()-1));
this.eventSource = this.tmp_events.filter((item)=>{
if(item.startTime >= this.monthViewData.selectedTime.setHours(0,0,0,0) && item.endTime <= this.monthViewData.selectedTime.getTime()){
return item;
}
});
}

(Ionic 2) Keep auto play in slides when the slide is swiped

i have the slider like this:
<ion-slides #promoSlider [options]="homeOptions" (change)="onPromoSlideChanged()" >
<ion-slide *ngFor="let promo of promos">
<img *ngIf="promo" src="{{promo.image}}" style="width:300px;height:300px;margin:auto;display:block" >
</ion-slide>
</ion-slides>
I have use this options to keep my slide playing using auto play:
homeOptions = {
initialSlide: 0,
loop: true,
autoplay:2000
};
But the problem is when i swipe the slider the auto play is stopped and the slider is not sliding again. How to keep the slider playing even i swipe the slider. I have try this code:
onPromoSlideChanged() {
alert('ABC');
this.promoSlider.options = this.homeOptions;
this.promoSlider.rapidUpdate();
//What should i do in this method?
};
What event i need to keep the slider slide again (keep playing) when i swipe the slider ? Thanks...
You can find your answer here => https://forum.ionicframework.com/t/how-to-keep-slides-auto-play-when-the-slides-is-swiped/54025/6
The official docs reference the component Swiper as the base of the ion-slides component, so the API should be the same as the one described in http://idangero.us/swiper/api/11.
You could use the option autoplayDisableOnInteraction to avoid disabling auto play after the user interaction.
Your options array should be:
homeOptions = {
initialSlide: 0,
loop: true,
autoplay:2000,
autoplayDisableOnInteraction: false
};
Hope it helps.
$scope.images = {"status":true,"msg":"2 record(s) found","sliders":[{"title":"slider 1","content":"test
value","weblink":null,"image":"http:\/\/192.168.8.54\/test\/media\/mbimages\/a\/m\/test.jpg"},{"title":"Slider
2","content":null,"weblink":null,"image":"http:\/\/192.168.8.54\/test\/media\/mbimages\/
a\/m\/test.png"}]}
<ion-slide-box delegate-handle="img-viewer" options="options" does-continue="true" loop="true" auto-play="true" slide-interval="5000" >
<ion-slide ng-repeat="nt in images" ng-if="nt.slider_position == '1'" >
<div class="box"><img ng-src="{{nt.image}}" style="width:400px;height:200px;margin:auto;display:block"/></div>
</ion-slide>
</ion-slide-box>
**Controller**
$scope.counter = 0;
$interval(function ()
{
if($scope.counter == $ionicSlideBoxDelegate.$getByHandle('img-viewer').currentIndex() + 1)
{
$ionicSlideBoxDelegate.$getByHandle('img-viewer').slide(0);
}
else{
$ionicSlideBoxDelegate.$getByHandle('img-viewer').update();
}
}, 2000);
angular.forEach($scope.images, function(value, key){
if(value.slider_position == "1")
{
$scope.counter++;
}
Using Observable works for your scenario. You can use it as -
import {Observable} from 'Rxjs/rx';
// in class -
#ViewChild(Slides) slides: Slides;
ionViewDidEnter() {
//you get slider data from any web service
this.sliderObservable = Observable.interval(3000).subscribe(x => {
this.autoPlaySlider();
// or you can do this, it will start autoplay at every 3 seconds
// this.slides.startAutoplay();
});
}
autoPlaySlider(){
var slider_index = this.slides.getActiveIndex();
if(slider_index < this.sliderData.length){
this.slides.slideTo(slider_index+1);
}
else{
this.slides.slideTo(0);
}
}
ionViewDidLeave(){
this.sliderObservable.unsubscribe();
}
You can find more reference Here

How to check ion-checkbox from database

I have this ionic tag already populated and with all items unchecked:
<ion-checkbox ng-repeat="categoria in listaCategorias"
ng-model="categoria.checked"
ng-checked="categoria.checked"
ng-change="recuperarServicos(categoria)">
{{ categoria.nmCategoria }}
</ion-checkbox>
And here my controller code that has a list of 'categoria ids':
//here I have the ids recovered from database that I split into an array of ids
var idsCategoria = $scope.meuanuncio.idsCategoria.trim().split(',');
if($scope.listaCategorias.length > 0)
{
//for each item in my listaCategorias (used in ng-repeat)
for (var i = 0; i < $scope.listaCategorias.length; i++) {
var item = $scope.listaCategorias[i];
//I compare id from each item with my list recovered from database
if(idsCategoria.indexOf($scope.listaCategorias[i].idCategoria) != -1)
{
//If the item id exist in database list, I check the item
item.checked = true;
// Below there are other ways that I tried to use
// $scope.listaCategorias[i].Selected = true;
// $scope.listaCategorias[i].checked = true;
$scope.listaCategorias[0].checked = true;
}
}
};
But I canĀ“t do my ion-checkbox item checked.
What am I doing wrong ?
Thanks.
ng-model="categoria.checked"
looks fine, don't think you need the ng-checked though.
var item = $scope.listaCategorias[i];
item.checked = true;
Nope, the item gets lost through the loop. I see you were trying with:
$scope.listaCategorias[i].checked = true;
Did you get an error or something? Because this looks like the way to do it.
Maybe try looping on a div around the ion-checkbox? aka
<div ng-repeat="categoria in listaCategorias">
<ion-checkbox ng-model="categoria.checked"
ng-change="recuperarServicos(categoria)">
{{ categoria.nmCategoria }}
</ion-checkbox>
</div>
try this :
<div ng-repeat="categoria in listaCategorias track by $index">
<ion-item class="item item-checkbox">
<label class="checkbox">
<input type="checkbox" ng-model="categoria.checked" ng-change="recuperarServicos(categoria)">
</label>
{{categoria.nmCategoria}}
</ion-item>
</div>
Controller:
$scope.recuperarServicos = function(categoria){
if(categoria.selected && ($scope.selectedItems.indexOf(categoria.name) < 0)){
$scope.selectedItems.push(categoria.name);
}else{
$scope.selectedItems.splice($scope.selectedItems.indexOf(categoria.name), 1);
}
};
hope this helps you..in someway..!
My problem was when I attribute my array of items to the $scope.listaCategorias.
I was doing that:
$scope.listaCategorias = listaCategorias;
But I need to do that:
$scope.listaCategorias.push.apply($scope.listaCategorias, listaCategorias);
I was building an array with the checked attribute inside, but when I associate my built list, I was associating the first one, which has not the checked attribute setted.
Let me show my code now.
My view :
<div ng-repeat="item in listaCategorias track by $index">
<ion-item class="item item-checkbox">
<label class="checkbox">
<input type="checkbox" ng-model="item.checked" ng-checked="item.checked" ng-change="recuperarServicos(item)">
</label>
{{ item.nmCategoria }}
</ion-item>
</div>
My controller:
//here I get all my 'categorias' from datatable
listaCategorias = appFactory.recuperarCategorias();
//If list is not null go ahead
if(listaCategorias != null) {
//split into an array all my 'categoria' ids
var idsCategoria = $scope.meuanuncio.idsCategoria.split(',');
//if list has items go ahead
if(listaCategorias.length > 0) {
for (var i = 0; i < listaCategorias.length; i++) {
//if 'categoria' id exists in datatable list set true, else false
if(idsCategoria.indexOf(listaCategorias[i].idCategoria) != -1) {
listaCategorias[i].checked = true;
}
else {
listaCategorias[i].checked = false;
}
}
};
//Here is the point !!! I need to load my $scope variable this way to build all my items correctly
$scope.listaCategorias.push.apply($scope.listaCategorias, listaCategorias);
}