ionic 3 calculate items after doing drag and drop - ionic-framework

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>

Related

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

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 ??

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;
}
}

ionic 3 youtube api data

I'm having a problem calling the data into the view. Console log is working as I included a screenshot.
ytapiUrl =https://www.googleapis.com/youtube/v3/playlistItems? part=snippet&playlistId='blahblahbla'
getECvideolists(){
return new Promise(resolve => {
this.httpClient.get(this.ytapiUrl).subscribe(ytdata => {
resolve(ytdata);
this.Ecvideos = ytdata;
console.log(ytdata);
}, err => {
console.log(err);
});
});
}
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let Ecvideo of Ecvideos">
<h2> ***this doesn't display*** {{Ecvideo.items.snippet.title}}</h2>
</ion-item>
</ion-list>
[
items key has an array so you need to iterate it through *ngFor
for example,
<ion-list *ngSwitchCase="'videos'">
<ion-item *ngFor="let item of Ecvideos.items">
<h2>{{item.snippet.title}}</h2>
</ion-item>
</ion-list>

How to make ionic 3 autoscroll for chat app work?

I have tried every solution but nothing has worked. I am building a chat app where i want it to be scrolled to last message automatically,also when new message comes it scrolls to the bottom.
I have tried scrollTo() on the #content but it doesn't work
chat.html
<ion-content #content *ngIf="buddy">
<div class = "chatwindow">
<ion-list no-lines *ngIf="allmessages">
<ion-item *ngFor = "let item of allmessages; let i = index" text-wrap>
<ion-avatar item-left *ngIf="item.sentby === buddy.uid">
<img src="{{buddy?.photoURL}}">
</ion-avatar>
<div class="bubble me" *ngIf="item.sentby === buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
<ion-avatar item-right *ngIf="item.sentby != buddy.uid">
<img src="{{photoURL}}">
</ion-avatar>
<div class="bubble you" *ngIf="item.sentby != buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
</ion-item>
</ion-list>
</div>
</ion-content>
chat.ts
#ViewChild('content') content: Content;
scrolltoBottom() {
setTimeout(() => {
// this.content.scrollToBottom();
}, 1000);
}
Your code should be like this.
export class ChatPage {
#ViewChild('content') content: Content;
constructor(public navCtrl: NavController) {
this.scrolltoBottom()
}
scrolltoBottom() {
setTimeout(() => {
this.content.scrollToBottom();
}, 300);
} }

Ionic update item inside page with http request

Happy new year for all of you.
I have a problem to update item in list using http request:
This is my code: in ts
ionViewWillEnter() {
const data = JSON.parse(localStorage.getItem('userData'));
this.userDetails = data.userData;
this.run_scriptsvis = setInterval(() => {
if (localStorage.getItem('sessionnewvisites') === '1') {
this.getnewvisit();
localStorage.removeItem('sessionnewvisites');
console.log('refresh');
} else {
console.log('no refresh');
}
}, 3000);
}
getnewvisit() {
return new Promise(resolve => {
this.http.request("https://website.fr/update.php).map(
res => res.json()).subscribe(datacool => {
console.log(datacool.resultcool);
this.datacool = datacool.resultcool;
console.log(this.datacool);
});
});
}
In my html i have this:
<ion-row no-padding>
<ion-col col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12>
<ion-list no-margin>
<ion-item-sliding *ngFor="let user of datacool" (ionSwipe)="delete(user)">
<ion-item style="min-height:10vh" class="cardcolor item-tittle" no-padding text-wrap (click)="openprofile(user.userid)">
<div item-left no-margin>
<img style="max-width: 80px;margin-left: 7px;" src="{{user.tnpicture}}">
</div>
<div item-top>
<h2 text-wrap><img src="{{user.online}}"> {{user.username}}</h2>
</div>
<div class="span-small">
{{user.age}} ans, {{user.gender}}
</div>
<div item-bottom>
<div class="span-small" text-left><ion-icon name="pin"></ion-icon> {{user.countyname}}</div>
<div></div>
<h3 left padding-left>{{user.date}}</h3>
</div>
</ion-item>
<ion-item-options>
<button ion-button expandable (click)="delete((user.id))" >delete</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-col>
</ion-row>
The code work good and do the update when there are new data.
The problem is that I don't want to revome the older item and replace it with the new.
I want the new item in the top and the old item in bottom of the new.
Thank you so much for helping me
Thanks i have found the solution
users2: any[] = [];
getnewvisit() {
return new Promise(resolve => {
this.http.request("https://website.fr/update.php).map(
res => res.json()).subscribe(datacool => {
console.log(datacool.resultcool);
this.datacool = datacool.resultcool;
for (let i = 0; i < this.datacool.length; i++) {
this.users2.push(this.datacool[i]);
}
console.log(this.datacool);
});
});
}