Ionic Printer it does not print a single element - ionic-framework

Hi guys i have this problem when i try to print an html item, but it also dispenses the whole page adding a call id does not function this is my code:
.html
<ion-row >
<ion-item *ngFor="let order of orders" id="pdf" >
<ion-icon name="mail-open" slot="start"></ion-icon>
<p> ordine: {{ order.id}}</p>
<p class="prob"> Indirizzo: {{ order.billing.address_1}} <br> Città: {{ order.billing.city}}
<br> Numero: {{ order.billing.phone}}</p>
<p class="prob"> Nome: <br> {{ order.billing.first_name}} {{ order.billing.last_name}}</p>
<button type="button" mat-button color="primary" (click)="printDocument()"></button>
</ion-item>
</ion-row>
.ts
import { Printer, PrintOptions } from '#ionic-native/printer/ngx';
printDocument() {
let options: PrintOptions = {
name: 'MyDocument',
duplex: true,
};
let content = document.getElementById('pdf');
this.printer.print(content, options);
}
and that's what happens:
print all page not a single item

Related

How to make ionic tab with two different function

So i have this code for list-company.page.html
<div class="tab_container" [ngSwitch]="tab" *ngFor="let i of company_data">
<ion-list lines="none" *ngSwitchCase="'list'" >
<ion-item (click)="sendCompany(i.id)">
<div class="item_container">
<div class="syllabus">
<h3>{{i.name}}</h3>
</div>
<ion-row>
<ion-col size="7">
</ion-col>
<ion-col size="5" class="ion-text-end">
<div class="follow">
Follow
</div>
</ion-col>
</ion-row>
</div>
</ion-item>
</ion-list>
ion-list lines="none" *ngSwitchCase="'status'">
<ion-item *ng-init='getFollowedCompany()'>
<!-- <ion-item (click)="sendCompany(i.id)"> -->
<div class="item_container">
<div class="syllabus">
<h3>{{i.name}}</h3>
</div>
<ion-row>
<ion-col size="7">
<!-- <p class="d-flex">{{i.jml}} Questions
<span></span>
{{i.waktu || 0}} mins
</p> -->
</ion-col>
<ion-col size="5" class="ion-text-end">
<div class="follow">
Unfollow
</div>
</ion-col>
</ion-row>
</div>
</ion-item>
</ion-list>
</div>
So the idea is the first tab named List is showing a list of company from my DB with function getCompany() and to pick a company to choose
and then the second tab named Status is showing the company that has been choosen from the List tab with function getFollowedCompany()
The problem is i dont know how to set this to different function in the html page
This is the code :
getCompany()
this.api_url='https://exam.graylite.com/api/company'
await this.storage.get('email').then((val) => {
this.email = val
});
// console.log(this.email);
var formData : FormData = new FormData();
formData.set('email',this.email);
this.http.post(this.api_url,formData)
.subscribe((response) => {
if(response['message']=='error'){
this.presentToast(response['message']);
} else {
this.company_data = response['data'];
// this.name = response['data']['name'];
// this.company_id = response['data']['company_id'];
console.log(this.company_data);
}
});
getFollowedCompany()
this.api_url='https://exam.graylite.com/api/getuserapproval'
await this.storage.get('email').then((val) => {
this.email = val
});
// console.log(this.email);
var formData : FormData = new FormData();
formData.set('email',this.email);
this.http.post(this.api_url,formData)
.subscribe((response) => {
if(response['message']=='error'){
this.presentToast(response['message']);
} else {
this.company_followed = response['data'];
// this.name = response['data']['name'];
// this.company_id = response['data']['company_id'];
console.log(this.company_followed);
}
});

ionic push notification opens page but in page navigation is messed up

Folks:
I have an ionic app that has a page where user can post comments on a story. If a user posts new comment, the comment is displayed in the page. Comments are fetched from a REST API using the "let comment of postComments" fragment with *ngFor.
<ion-content *ngIf="!searchUser" #myContent padding [scrollEvents]="true">
<ion-refresher slot="fixed" (ionRefresh)="reloadPage($event)">
<ion-refresher-content pullingIcon="arrow-dropdown" refreshingSpinner="circles" refreshingText="Refreshing..." >
</ion-refresher-content>
</ion-refresher>
<div class="post-content">
<ion-item lines="none" no-padding>
<ion-avatar slot="start">
<img [src]=" (profileUrl == null) ? 'assets/img/emptyperson.jpg' : profileUrl">
</ion-avatar>
<p class="user-post-text">
<strong>{{
username
}}</strong><span>
{{ description }}
</span>
</p>
</ion-item>
<div class="border"></div>
<ion-item-sliding class="comments-container" *ngFor="let comment of postComments; let i = index; let c = count;" [id]="'slidingItem' + i">
<ion-item no-padding lines="none">
<ion-avatar slot="start">
<img [src]=" (comment.profileUrl == null) ? 'assets/img/emptyperson.jpg' : comment.profileUrl">
</ion-avatar>
<p>
<strong>{{
comment.username
}}</strong>
{{ comment.comment }}
</p>
<ion-button
slot="end"
fill="clear"
(click)="likeButton(comment.id, comment.currentUserLike)"
[disabled]="disableLikeButton"
>
<ion-icon
*ngIf="!comment.currentUserLike"
slot="icon-only"
name="heart-outline"
color="black"
></ion-icon>
<ion-icon
*ngIf="comment.currentUserLike"
slot="icon-only"
name="heart"
color="danger"
></ion-icon>
</ion-button>
<br/>
</ion-item>
<ion-item-options *ngIf="isPostMine && (comment.userId != userdetails.id)">
<ion-item-option color="danger" >
<button color="danger" [disabled]="disableDeleteButton" (click)="removeComment(comment.id,i)"><ion-icon class="inside-icon" name="trash"></ion-icon></button>
</ion-item-option>
<ion-item-option color="primary" >
<button color="primary" (click)="reportOffensive(comment.id,i)"><ion-icon class="inside-icon" name="remove-circle"></ion-icon> </button>
</ion-item-option>
</ion-item-options>
<ion-item-options *ngIf="isPostMine && (comment.userId == userdetails.id)">
<ion-item-option color="danger" >
<button color="danger" [disabled]="disableDeleteButton" (click)="removeComment(comment.id,i)"><ion-icon class="inside-icon" name="trash"></ion-icon></button>
</ion-item-option>
</ion-item-options>
<ion-item-options *ngIf="!isPostMine && (comment.userId != userdetails.id)">
<ion-item-option color="primary" >
<button color="primary" (click)="reportOffensive(comment.id,i)"><ion-icon class="inside-icon" name="remove-circle"></ion-icon> </button>
</ion-item-option>
</ion-item-options>
<ion-item-options *ngIf="!isPostMine && (comment.userId == userdetails.id)">
<ion-item-option color="danger" >
<button color="danger" [disabled]="disableDeleteButton" (click)="removeComment(comment.id,i)"><ion-icon class="inside-icon" name="trash"></ion-icon></button>
</ion-item-option>
</ion-item-options>
<p class="all-comments">
<span class="grey-text"> {{ comment.createdAt | timeAgo }}</span>
<span *ngIf="comment.numLikes > 0" class="grey-text tab" (click)="userList(comment.id,'CommentLikes')">{{comment.numLikes}} likes</span>
</p>
</ion-item-sliding>
</div>
</ion-content>
<ion-footer>
<ion-item lines="none">
<ion-avatar slot="start">
<img src="{{ userProfileUrl }}" />
</ion-avatar>
<ion-textarea autocapitalize="sentences" maxLength="255" type="text"
[(ngModel)]="commentContent" (ionChange)="getUsers($event)"
rows="1"
placeholder="Add a comment"
></ion-textarea>
<ion-icon class="blueicon" slot="end" name="send" (click)="addComment()"></ion-icon>
</ion-item>
</ion-footer>
In my typescript, I have a function addComment() which refreshes the value of postComments so that the page automatically reloads.
addComment() {
if (this.commentContent.trim()) {
this.showLoader("Posting Comment ...");
this.userPostComment.comment = this.commentContent;
this.userPostCommentJSON = JSON.stringify(this.userPostComment);
//console.log("Comment JSON is "+this.userPostCommentJSON);
this.https.post(this.serviceUrl+'comments',this.userPostCommentJSON,this.httpOptions)
.subscribe(
(res: any)=>{
this.commentContent = "";
this.refresh();
setTimeout(() => {
console.log("In Timeout");
this.refreshPostComments("");
this.events.publish('postComment:created', {
id: res.id,
time: new Date()
});
this.hideLoader();
this.commentContent = "";
},2000)
},
err => {
this.hideLoader();
this.showAlert(err);
}
);
}
}
This is working like charm, when I get to the Comments page from the story.
Here is my problem. If I navigate to the Comments page from a oneSignal push notification, everything works fine up to the point where I enter a new comment. When I enter a new Comment, the comment is created in the database using the RESTAPI (works fine), the refreshPostComments method is called in typescript (works fine), but my view does not get updated till I physically click the comment box again.
I don't know what I am doing wrong. But in my app.component.ts, I check for oneSignal notification clicked and if clicked, I do this
if (localStorage.getItem('auth-user') != undefined || null) {
if (additionalData.type == "comment") {
await console.log("Going to Comments");
this.router1.navigateForward(['/comments', {
userId: parseInt(additionalData.userId),
username: additionalData.username,
userPostId: parseInt(additionalData.userPostId),
description: additionalData.description,
profileNameKey: additionalData.profileNameKey
}]);
}
That works. Takes me to the Comments Page. But once I am in the page, I can do virtually everything else like peach, except if I add a comment, then it does not reflect in real time.
Any pointers on what I am missing?
JR
Found my solution. I think Angular’s Change detection is triggered by certain events, and when I was navigating to the page from OneSignal's notification - whatever OneSignal was using, it was not getting on Angular's radar. So I had to import ChangeDetectorRef and do a manual detectChanges() to make sure ngFor would detect the changes as soon as they occur.
Phew. Spent almost a half a day on this. So much for OneSignal and Angular's quirks with OneSignal. And Ionic had nothing to do with it.
Regards,
JR

CheckBox Function calling a button with IONIC 2

I'm simulating something like a shopping cart using ionic 2. Basically you write the item's name and value and it's creating a list with checkbox as in the image below.
But I wanted the option only appear when selecting one of the checkboxes, and did not stay static on the screen as it is now. How can I do this?
grid calling the CheckBox:
<ion-grid>
<ion-row *ngFor="let item of produto">
<ion-item>
<ion-label (click)="clicou(item.desc)">
{{ item.desc }} {{ item.valor }}
</ion-label>
<ion-checkbox checked="false"></ion-checkbox>
</ion-item>
</ion-row>
</ion-grid>
button code part:
<button ion-button block (click)="remove()" color="danger" style="transition: none 0s ease 0s;">
<span class="button-inner">
<ion-icon name="close"></ion-icon>
Remover Selecionados
</span>
<div class="button-effect"></div>
</button>
in ts create a variable that contains the value of the checks, as an example I will use productState which will be boolean type, and create in produto a state.
you can use a ngmodel and the variable already created (productState) to validate the status of the product, and use the event (ionchange) to this
<ion-grid>
<ion-row *ngFor="let item of produto">
<ion-item>
<ion-label (click)="clicou(item.desc)">
{{ item.desc }} {{ item.valor }}
</ion-label>
<ion-checkbox (ionChange)="validState()" [(ngModel)]="productState" ></ion-checkbox>
</ion-item>
</ion-row>
in ts create a function to valid the state of products:
validState(){
let cont = 0;
for (let index = 0; index < this.produto.length; index++) {
if (this.produto[index].State){
cont++;
}
}
if(cont >=1){
this.productState = true;
}else{
this.productState = false;
}
}
and in the button we will use ngIf to validate the product status through productState
<button *ngIf="productState" ion-button block (click)="remove()" color="danger" style="transition: none 0s ease 0s;">
<span class="button-inner">
<ion-icon name="close"></ion-icon>
Remover Selecionados
</span>
<div class="button-effect"></div>
</button>
ngIf docs
ngmodel docs

When there is no text on ion-search bar the list should hide?

i stuck , please help me
I am using ion-searchbar , i want that when there is no text on the searchbar the list must be hide but the list is still showing
Can anyone help me?
in .html file
<ion-searchbar (ionInput)="getItems($event)" class="" style="background-color: #073262 !important" [showCancelButton]="shouldShowCancel" style="background:none!important;"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of items" (click)="openNavDetailsPage(item)">
{{ item }}
</ion-item>
</ion-list>
in .ts file
getItems(ev) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the ev target
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
You can use ngModel and ngIf :
<ion-searchbar [(ngModel)]="searchInput" (ionInput)="getItems($event)" class="" style="background-color: #073262 !important" [showCancelButton]="shouldShowCancel" style="background:none!important;"></ion-searchbar>
<ion-list *ngIf="searchInput !== ''">
<ion-item *ngFor="let item of items" (click)="openNavDetailsPage(item)">
{{ item }}
</ion-item>
</ion-list>
in .ts:
public searchInput='';
OR
If your variable items is empty at initalization :
<ion-searchbar (ionInput)="getItems($event)" class="" style="background-color: #073262 !important" [showCancelButton]="shouldShowCancel" style="background:none!important;"></ion-searchbar>
<ion-list *ngIf="items && items.length">
<ion-item *ngFor="let item of items" (click)="openNavDetailsPage(item)">
{{ item }}
</ion-item>
</ion-list>
in .ts:
public items = [];

Ionic - show splash screen until the first image loads

I have an app in Ionic v.1 and on page where I have a list of articles, I would like to have a splash screen until the first image is completely loaded, not sure how to do that?
This is the controller:
module.exports = angular.module('coop.controllers')
.controller('ArticlesController', function($scope, ArticleService, $state, $ionicScrollDelegate, $location, $ionicPosition, $ionicConfig) {
$scope.articles = ArticleService.all();
$scope.$on('$ionicParentView.afterEnter', function(event, data) {
$scope.videoPlaying = [];
$ionicConfig.views.swipeBackEnabled(false);
if (data.direction == 'back') {
$scope.doRefresh();
}
});
$scope.articleType = 'all';
$scope.articleFilter = function(button) {
$scope.articleType = button;
$scope.doRefresh();
};
$scope.showBulletPoint = function(which) {
return $scope.articleType == which;
}
$scope.like = function(article){
article.userLiked = !article.userLiked;
ArticleService.like(article)
};
$scope.doRefresh = function (){
var articleType = $scope.articleType ? $scope.articleType : 'all';
ArticleService[articleType]().$promise.then(function(data){
$scope.articles = data;
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.videoPlaying = [];
$scope.playerVars = {
controls: 0,
showinfo: 0
};
$scope.playVideo = function(youtubePlayer, index) {
$scope.videoPlaying[index] = true;
youtubePlayer.playVideo();
};
$scope.$on('$ionicView.afterLeave', function(event, data) {
$scope.videoPlaying = false;
$ionicConfig.views.swipeBackEnabled(true);
//youtubePlayer.stopVideo();
});
});
And this the html:
<ion-view>
<div class="row articles-header">
<button menu-toggle="left" class="button button-icon icon ion-navicon-round"></button>
<div class="right-icons">
<!--<a class="button button-icon icon ion-ios-search-strong">
</a>-->
<a class="button button-icon" href="#" ng-click="articleFilter('all')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('all')"></i> Siste
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('video')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('video')"></i> Video
</a>
<a class="button button-icon" href="#" ng-click="articleFilter('popular')"><i class="ion-ios-circle-filled" ng-show="showBulletPoint('popular')"></i> Populært
</a>
</div>
</div>
<ion-content class="articles-content">
<ion-refresher pulling-icon="false" on-refresh="doRefresh()">
</ion-refresher>
<ion-list>
<ion-item ng-repeat="article in articles" class="item-light">
<div class="article">
<a ng-if="authenticated" ng-show="article.external_media.length == 0" ui-sref="main.article({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ng-if="!authenticated" ng-show="article.external_media.length == 0" ui-sref="main.articlePublic({id: article.id})" nav-direction="forward" class="article-image-link">
<img class="img" src="{{ fileServer }}/imagecache/cover/{{article.cover_image}}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
</a>
<a ui-sref="main.article({id: article.id})">
<div class="iframe" ng-show="article.external_media.length > 0 && article.external_media.image != ''">
<img class="img" ng-src="{{ article.external_media[0].image }}">
<h1>{{ article.title.split(' ', 7).join(' ') }}</h1>
<div class="iframe-overlay">
<div class="play">
<img class="playButton" src="icons/playRectangle.svg"/>
</div>
</div>
</div>
</a>
</div>
<div class="row article-meta" ng-class="{ 'has-comments': article.enable_comments }">
<a ng-click="like(article)" class="subdued col col-30">
<img class="social-images" ng-src="icons/{{ article.userLiked ? 'heart' : 'heart-outline' }}.svg"/> Lik
</a>
<a ui-sref="main.article({id: article.id, gotoComments: true })" class="subdued col col-60" ng-if="article.enable_comments">
<img class="social-images" src="icons/comment.svg"/> {{ article.commentCount }} Kommentarer
</a>
<a ui-sref="main.article({id: article.id})" nav-direction="forward" class="col col-10 article-link right">
<img class="social-images" src="icons/arrow.svg"/>
</a>
</div>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
One approach is to attach an onLoad handler to the images, and when the first image (or any other specific image, all, etc) have loaded you can remove your splash screen.
To do this we'll create a directive to handle the onload event, based on this outstanding solution from Peter, combined with the $ionicLoading loader.
var app = angular.module('app', ['ionic'])
app.controller('appCtrl', function($scope, $timeout, $ionicLoading) {
// Setup the loader
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
// Add a simple onLoad callback
$scope.onLoad = function (id) {
if (id === 0) {
$ionicLoading.hide();
}
}
$scope.items = [
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'},
{img: 'http://placehold.it/5000x8000/f9009a/ffffff'}
];
});
// The imageonload directive
app.directive('imageonload', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
Then use the directive:
<ion-item ng-repeat="item in items" href="#">
<img ng-src="{{item.img}}" imageonload="onLoad({{$index}})" id="img-{{$index}}" />
</ion-item>
When the app loads the $ionicLoading screen will be shown until the first image emits the onload event, causing the $ionicLoading screen to be removed.
For a working demo, see this Ionic Play demo.
The loading screen may only be noticeable the first time you load the demo, and on subsequent loads you might need to do a hard refresh.