Ionic 3 : How to make checkboxes behavior like radio-button - ionic-framework

I have a list of checkboxes and I want to make them behave like radio button
How can I do this?
I tried using radio button but I am not getting the value of the user input so I dropped the idea of radio button and implement checkbox where i get the proper value & everything is perfect except the multiple checkbox selection I want to remove that
Here is my code:
selectOption(name, isChecked) {
if (isChecked === true) {
this.selectednames.push(name);
} else {
let index = this.removeCheckedFromName(name);
this.selectednames.splice(index, 1);
}
}
removeCheckedFromName(names: String) {
return this.selectednames.findIndex((ref) => {
return ref === names;
});
}
in my HTML
<ion-list>
<ion-list-header>
Choose Your Team
</ion-list-header>
<ion-item *ngFor="let names of name; let i = index">
<ion-label>{{name}}</ion-label>
<ion-checkbox item-left color="secondary" formControlName="name"
(ionChange)="selectOption(name, $event.checked)">
</ion-checkbox>
</ion-item>
</ion-list>
Any advices is highly appreciated

checkbox-stovr.page.html
<ion-header>
<ion-toolbar>
<ion-title>checkbox-stovr</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>
Choose Your Team
</ion-list-header>
<ion-item *ngFor="let name of names; let i = index">
<ion-label>{{ name['name'] }}</ion-label>
<ion-checkbox [(ngModel)]="name['isChecked']" (click)="toggle(name)">
</ion-checkbox>
</ion-item>
</ion-list>
</ion-content>
CheckboxStovrPage
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-checkbox-stovr',
templateUrl: './checkbox-stovr.page.html',
styleUrls: ['./checkbox-stovr.page.scss'],
})
export class CheckboxStovrPage implements OnInit {
names = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' },];
public selected: string;
constructor() { }
ngOnInit() {
}
public toggle(selected) {
for (let index = 0; index < this.names.length; index++) {
if (this.names['name'] != selected['name'])
this.names[index]['isChecked'] = null;
}
}
}

Do you want only one value selected at a time ??

Related

Ion-item with *ngFor in a dropdown

I would like to set a button that opens and hides some ion-item in a dropdown.
I know that there might be a solution in the docs but I am unable to find it
<ion-header>
<ion-toolbar>
<ion-title>Technical Information</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>
<ion-label>Manuales</ion-label>
</ion-list-header>
<ion-item *ngFor="let m of manuals">
<ion-label>{{m}}</ion-label>
</ion-item>
</ion-list>
<!-- Other <ion-list-header>s and <ion-item>s -->
</ion-content>
I would like to hide and show all Items when clicking on each ion-list-header, show his own ion-item with *ngFor, like if there are 20 manuals, dropdown all 20 manuals and hide others ion-list-headers...
Is there a way to do it with this structure or maybe with another?
Try this:
<ion-header>
<ion-toolbar>
<ion-title>Technical Information</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list *ngFor="let m of manuals; let i=index">
<ion-list-header>
<ion-label (click)="showOrHide(i)">Manuales</ion-label>
</ion-list-header>
<ion-list id="{{i}}" style="display:none">
<ion-item *ngFor="let m of m.list">
<ion-label>{{m}}</ion-label>
</ion-item>
</ion-list>
</ion-list>
</ion-content>
In .ts component:
import { Component } from '#angular/core';
import { NavController , AlertController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
manuals = [{
id:1,
list: ["1","2","3"]
},
{
id:2,
list: ["1","2","3"]
},
{
id:3,
list: ["1","2","3"]
},
{
id:4,
list: ["1","2","3"]
}]
constructor() {
}
showOrHide(id){
const listItemShow = document.getElementById(id);
if(listItemShow.style.display === "none")
listItemShow.style.display = "block"
else
listItemShow.style.display = "none"
}
}

ionic 3 calculate items after doing drag and drop

I'm very new in software project and currently working on final year project, mobile apps using ionic 3 framework. I have drag and drop function, first bucket with list of items and second bucket is empty. When I want to drag the items from 1st bucket to the 2nd bucket, I want to calculate the price for each entry at the second bucket but I really don't have idea to do it. Can someone help me with the codes :(
this is my calculate.ts
q1 = [];
q2 = [];
details: any = [];
totalPrice: number;
constructor(public navCtrl: NavController, private postPvdr: PostProvider, public navParams: NavParams, public dragulaService: DragulaService, public AlertController:AlertController) {
dragulaService.drop().subscribe((value) => {
console.log(value)
});
const bag: any = this.dragulaService.find('bag');
if (bag !== undefined ) this.dragulaService.destroy('bag');
this.dragulaService.createGroup('bag', {
revertOnSpill: true,
});
}
ionViewDidLoad() {
this.details = [];
this.getlist();
this.getTotalPrice()
}
getlist(){
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.details.push(detail);
console.log(data);
}
});
}
getTotalPrice(){
let totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
totalPrice += Number.parseFloat(detail.dest_budget);
}
});
console.log(totalPrice);
return totalPrice;
}
these lines of codes seem weird because i just do try n error
this is my calculate.html
<ion-content padding>
<ion-row>
<ion-col width-50 class="left">
<div class="header">First Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="details">
<button ion-item *ngFor="let detail of details">
{{detail.dest_name}}
<p>{{ detail.dest_budget}}</p>
</button>
</ion-list>
</ion-col>
<ion-col width-50 class="right">
<div class="header">Second Bucket</div>
<ion-list [dragula]='"bag"' [(dragulaModel)]="q2">
<div ion-item *ngFor="let detail of q2">
{{detail.dest_name}}
<p>{{ detail.dest_budget }}</p>
</div>
</ion-list>
</ion-col>
</ion-row>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:</ion-title>
</ion-toolbar>
</ion-footer>
the total price should be showing at the footer
here is my interface looks like
hope someone can help :)
call function here
dragulaService.drop().subscribe((value) => {
this.getTotalPrice();
});
modify the function
getTotalPrice(){
this.totalPrice = 0;
let body = {
aksi: 'get_user'
};
this.postPvdr.postData(body, 'aksi_user.php').subscribe(data => {
for(let detail of data.result){
this.totalPrice += Number.parseFloat(detail.dest_budget);
}
});
}
and bind model
<ion-footer>
<ion-toolbar>
<ion-title>Total Price:{{totalPrice}}</ion-title>
</ion-toolbar>
</ion-footer>

Switching one icon button switches all icon buttons in my share post

I am making ionic project in my project i want to add double tab likes button .My proble is when tap on image then show likes icon for all post .I want to show only likes post icon .How can resolve this please help me below are my code which is used for likes icon..
tab1.page.html
<ion-header>
<ion-toolbar color="secondary">
<ion-title style="border: 1px solid #ccc" (click)="scrollToTop()">Pictagram</ion-title>
</ion-toolbar>
</ion-header>
<ion-content cache-view="false">
<ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-refresher-content
pullingIcon="arrow-dropdown"
pullingText="Pull to refresh"
refreshingSpinner="circles"
refreshingText="Refreshing...">
</ion-refresher-content>
</ion-refresher>
<hr no-margin no-padding>
<div (swipe)="swipePage($event)">
<!-- Cards -->
<ion-card no-padding padding-bottom no-margin class="card" *ngFor="let getImage of getImages3">
<ion-row>
<ion-col col-10>
<ion-item>
<ion-avatar item-left>
<img *ngIf="getImage.sex == 'male'" src="http://localhost:8000/files/{{getImage.image || 'avatar2.png'}}">
<img *ngIf="getImage.sex == 'female'" src="http://localhost:8000/files/{{getImage.image || 'Female-Avatar.jpg'}}">
</ion-avatar>
<b style="width: 222px;display: -webkit-box;padding-left: 11px;">{{getImage.name}}</b>
</ion-item>
</ion-col>
<ion-col col-2>
</ion-col>
</ion-row>
<div>
<img src="http://localhost:8000/files/{{getImage.image || 'avatar2.png'}}" (click)="tapPhotoLike(getImage.id)">
</div>
<p no-margin no-padding>
<button clear ion-button icon-only class="like-btn">
<ion-icon no-padding [name]="like_btn.icon_name" color="{{ like_btn.color }}" class="icon-space"></ion-icon>
</button>
</p>
<ion-card-content class="padding">
<p class="like-content">
<ion-icon class="color" name="heart" ></ion-icon> {{getcounts}} likes
</p>
<p><b>{{getImage.title}}</b>{{getImage.info}}</p>
<ion-note style="font-size: 12px">
{{getImage.created_at | timeAgo}}
</ion-note>
</ion-card-content>
</ion-card>
</div>
</ion-content>
In tab1.page.ts file i am manage the icon please help me how to show icon only for liked post. how to set id please help me...
tab1.page.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { User } from '../user';
import { first } from 'rxjs/operators';
import { Storage } from '#ionic/storage';
import { ToastController } from '#ionic/angular';
import { LoadingController } from '#ionic/angular';
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
getImages: User[] = [];
getImages2: User[] = [];
getImages3;
getcounts;
countLikes
counts
unlikes
public like_btn = {
color: 'danger',
icon_name: 'heart-empty'
};
public tap: number = 0;
constructor(private userService: UserService,
public toastController: ToastController,
private storage: Storage,
public loadingController: LoadingController) {
}
doRefresh(event) {
this.userPost();
setTimeout(() => {
event.target.complete();
}, 2000);
}
ngOnInit() {
this.userPost();
this.getCountOfLikes();
}
async userPost() {
const loading = await this.loadingController.create({
message: 'Please wait...',
spinner: 'crescent',
duration: 2000
});
await loading.present();
this.userService.getUserPost().pipe(first()).subscribe(getImages => {
this.getImages3 = getImages;
//console.log(this.getImages3);
loading.dismiss();
});
}
likeButton() {
const detail_id = this.userService.getCurrentIdpostId();
if (this.like_btn.icon_name === 'heart-empty') {
this.like_btn.icon_name = 'heart';
this.like_btn.color = 'danger';
this.storage.get('userId').then((val) => {
if (val) {
this.userService.userPostLikes(val, detail_id).pipe(first()).subscribe(
async data => {
//console.log(data);
if (data['status'] === 'you have already liked this post') {
const toast = await this.toastController.create({
message: 'you have already liked this post',
duration: 2000
});
toast.present();
}
this.getCountOfLikes();
}
);
}
});
}
else {
this.like_btn.icon_name = 'heart-empty';
this.like_btn.color = 'danger';
this.unlikePost();
this.getCountOfLikes();
}
}
tapPhotoLike($detail_id) {
this.userService.setCurrentIdpostId($detail_id);
this.tap++;
setTimeout(() => {
if (this.tap == 1) {
this.tap = 0;
//alert('Single Tap');
} if (this.tap > 1) {
this.tap = 0;
this.likeButton();
//alert('Double Tap');
}
}, 250);
}
ionViewWillEnter() {
this.userPost();
this.getCountOfLikes();
}
getCountOfLikes() {
this.userService.getCountId().pipe(first()).subscribe(likes => {
this.counts = likes;
for (var k in this.counts) {
var i = this.counts[k].detail_id;
}
this.userService.getUserPostlikes(i).pipe(first()).subscribe(getlikes => {
this.getcounts = getlikes;
});
});
}
unlikePost() {
let detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
this.userService.unLikes(val, detail_id).subscribe(async dislikes => {
this.unlikes = dislikes;
})
}
});
}
}
This is an general example of how you can fix your shared button problem.
We are going to make an array which will toggle values. The array will be the size of the data array. Inside we will place all values to false.
If a button is clicked, the index of the data array will be passed and this will change the value of the toggle array to true.
HTML
Looping over the data array with index i
<ion-item *ngFor="let image of images; index as i">
<ion-button (click)="toggleIcon(i)">
<ion-icon name="heart-empty" *ngIf="!iconToggle[i]"></ion-icon>
<ion-icon name="heart" *ngIf="iconToggle[i]"></ion-icon>
</ion-button>
</ion-item>
TS
If we get the data from the subscribe, we set the toggle array to all false values.
If the button is clicked, the value of the same index as the data array changes to true and the other icon can be showed in html.
images = []
iconToggle = [];
this.userService
.getUserPost()
.subscribe(res => {
this.images = res;
this.setIconToggles();
});
setIconToggles() {
let x = 0;
this.images.forEach(() => {
this.iconToggle[x] = false;
x++;
});
}
toggleIcon(num: number) {
if (this.orderToggle[num]) {
this.orderToggle[num] = false;
} else {
this.orderToggle[num] = true;
}
}

How to get modal data on modal dismiss in Ionic 3?

I have a Page with a List. From that page I open a MODAL.
That modal contains a Text box and a Add Item Button.
When I enter an Item in the Box and Hit Add Item, I need to
1) Dismiss the Modal
2) Add the entered Item in the List in the Previous List
I need to do this via On Dismiss().
HOME.HTML
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let grocery of itemsArray">{{grocery}}</ion-item>
</ion-list>
<button ion-button round (click)="addItem()">Add Item</button>
</ion-content>
HOME.TS
export class HomePage {
public itemsArray = [];
newItem: String;
constructor(public navCtrl: NavController, public modalCtrl: ModalController, public navParams: NavParams) {
}
ionViewDidLoad() {
this.newItem = this.navParams.get('data');
this.itemsArray = [
'Bread',
'Milk',
'Cheese',
'Snacks',
'Apples',
'Bananas',
'Peanut Butter',
'Chocolate',
'Avocada',
'Vegemite',
'Muffins',
'Paper towels'
];
this.itemsArray.push(this.newItem)
}
public addItem() {
let modalPage = this.modalCtrl.create(ModalPage);
modalPage.onDidDismiss(data => {
this.newItem = data;
});
modalPage.present();
}
}
MODAL.HTML
<ion-header>
<ion-navbar>
<ion-title>Add Item</ion-title>
<ion-buttons end>
<button ion-button (click)="closeModal()">Close</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label>Item</ion-label>
<ion-input type="text" [(ngModel)]="newItem"></ion-input>
</ion-item>
<button ion-button color="secondary" (click)="add()">Add Item</button>
</ion-list>
</ion-content>
MODAL.TS
export class ModalPage {
name:any;
constructor(public navCtrl: NavController, public viewCtrl: ViewController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ModalPage');
}
public closeModal() {
this.viewCtrl.dismiss();
}
add() {
let data = {"name": this.name};
this.viewCtrl.dismiss(data)
}
}
Your code seems to be fine overall.
Change this part.
public addItem() {
let modalPage = this.modalCtrl.create(ModalPage);
modalPage.onDidDismiss(data => {
this.itemsArray.push(data);
});
modalPage.present();
}
Change the name of your variable on the html or the TS file.
name to newItem or vice-versa
You are using [(ngModel)]="newItem" but in your TS file your using this.name
You're adding the item on ionViewDidLoad() but the new item arrives at modalPage.onDidDismiss()
Give it a try. I'll help you further if it still does not work.
First you need to pass object/string of item/data from you mode while you are closing the same
this.viewCtrl.dismiss(data);
And you have to subscribe model closing event at the page from where you have opened it for ex.
let modal = this.modalCtrl.create(ModelPage);
modal.onDidDismiss(data => {
this.badge = data;
});
modal.present();
After you can simply push you new item in to items array :)

Dynamic dropdown not working properly in ionic 3

You can change here also ->https://stackblitz.com/edit/ionic-djze7u
home.html
<ion-content padding>
<ion-card>
<ion-card-content *ngFor="let item of users">
<ion-row>
<ion-label>{{item.name}}:</ion-label>
<ion-label>{{item.age}}</ion-label>
Here is the loop which I want to show value into dropdown according to item.term
<ion-select [(ngModel)]="check[item.age]">
<ion-option value="0" selected>0</ion-option>
<ion-option *ngFor="let v of caldrop(item.term)" value="{{v}}">
{{v}}
</ion-option>
</ion-select>
</ion-row>
</ion-card-content>
</ion-card>
</ion-content>
Home.ts
export class HomePage {
according to this term vale dropdown will show from 0 to this term value
users:any = [
{ name: 'Composite Factory', age: 1, term:2 },
{ name: 'Todd', age: 2, term:1 },
{ name: 'Lisa', age: 3, term:4 }
];
check:any = [];
constructor(public navCtrl: NavController) {
}
caldrop(myval:any){
console.log(myval)
let myarr:any = [];
for(let i=1;i<=myval;i++){
myarr.push(i);
}
return myarr;
}
}