Customization in Ionic Bottom Sheet - ionic-framework

I am trying to add list in bottom sheet but ionic gave us an array so we can add class there and style it.
What i am trying to ask is how we can make a list or totally our own html code and pass it to bottom sheet function that will just display?
async presentActionSheet() {
const actionSheet = await this.actionSheetController.create({
header: 'Albums',
buttons: [{
text: 'Delete',
role: 'destructive',
icon: 'trash',
handler: () => {
console.log('Delete clicked');
}
}, {
text: 'Share',
icon: 'share',
handler: () => {
console.log('Share clicked');
}
}, {
text: 'Play (open modal)',
icon: 'arrow-dropright-circle',
handler: () => {
console.log('Play clicked');
}
}, {
text: 'Favorite',
icon: 'heart',
handler: () => {
console.log('Favorite clicked');
}
}, {
text: 'Cancel',
icon: 'close',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}]
});
await actionSheet.present();
}
It is by default action sheet, what i want is to make it in DOM. I have found the similar question here with no answer Similar Question URL Please see what i need...!
What i need

Try with Modal Component
home.page.html
<ion-button (click)="OpenModel()">
Open Modal (Bottom)
<ion-icon mode="ios" name="arrow-forward"></ion-icon>
</ion-button>
home.page.ts
import { ModalController } from '#ionic/angular';
import { ModalpagePage } from '../modalpage/modalpage.page';
constructor(private modalCtrl: ModalController) {}
async OpenModel(){
const presentModel = await this.modalCtrl.create({
component: ModalpagePage,
componentProps: {
title: 'Billing Address',
type:'billing',
},
showBackdrop: true,
mode: "ios",
cssClass: 'change-address-shipping-modal'
});
presentModel.onWillDismiss().then((data)=>{
console.log(data);
//custom code
});
return await presentModel.present();
}
modalpage.page.html
<ion-header>
<ion-toolbar text-center>
<ion-title>
Modal title
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div>
HTML CODE HERE
</div>
</ion-content>
Declare in app.module.ts
declarations: [AppComponent, ModalpagePage],
entryComponents: [ModalpagePage],
Global.scss
.change-address-shipping-modal{
--height:60%;
align-items: flex-end;
}
ScreenShot
Demo

Currently action sheet does not allow you to add html code in it. This feature is however requested you can see here https://github.com/ionic-team/ionic/issues/16718

Try <ion-card>
<ion-header> </ion-header>
<ion-content> </ion-content>
<ion-card> </ion-card>
<ion-footer> </ion-footer>
you can use *ngIf to control ion-card
example:
in page.ts
showCard:Boolean = true;
constructor(){}
ngOnInit() {}
in page.html
<ion-card *ngIf="showCard"> </ion-card>
https://ionicframework.com/docs/api/card

Related

How to Manage Session in side menu in Ionic 4?

Ionic app with a side menu
Here my app concept is Blog App
in this I need to log-in, profile, etc
Ionic app with a side menu
if user want to like or comment any blog post he must log-in first
so I want to manage session if the already log-in user so hide log-in ion-item from side menu else logout ion-item vise-Versa
Here is code
home.html
<ion-app>
<ion-split-pane contentId="main-content" >
<ion-menu contentId="main-content" >
<ion-header>
<ion-toolbar color="primary">
<ion-title>Lady Help Lady</ion-title>
</ion-toolbar>
</ion-header>
<ion-content color="primary">
<ion-list >
<ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
<ion-item color="primary" [routerDirection]="'root'" [routerLink]="[p.url]">
<ion-icon slot="start" [name]="p.icon" color="light"></ion-icon>
<ion-label color="light">
{{p.title}}
</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false" >
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()" > Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>
</ion-content>
</ion-menu>
<ion-router-outlet id="main-content"></ion-router-outlet>
</ion-split-pane>
</ion-app>
home.page.ts
import { Component, OnInit } from '#angular/core';
import { Router} from '#angular/router';
import { MenuController } from '#ionic/angular';
import { AuthService } from '../services/auth.service';
import { StorageService } from '../services/storage.service';
#Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
public appPages = [
{
title: 'Blog',
url: '/home/blog',
icon: 'home'
},
{
title: 'Profile',
url: '/home/profile',
icon: 'cog'
},
{
title: 'Change Password',
url: '/home/change-password',
icon: 'lock'
},
{
title: 'About Us',
url: '/home/about-us',
icon: 'cog'
},
{
title: 'Privacy Policy',
url: '/home/privacy-policy',
icon: 'settings'
}
,
{
title: 'Terms & Conditions',
url: '/home/terms-conditions',
icon: 'paper'
},
{
title: 'Enable Location',
url: '/home/enable-location',
icon: 'pin'
}
,
{
title: 'Donation',
url: '/home/donation',
icon: 'card'
}
];
public authUser: any;
showBtnLogin = true;
// showBtnLogout: boolean = true;
currentUser: any;
constructor(private router: Router,
private authService: AuthService,
private menu: MenuController,
public storageService: StorageService) { }
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
if (res === null) {
console.log(res);
this.showBtnLogin = false;
} else {
this.showBtnLogin = true;
}
});
}
logout() {
this.authService.logout();
}
login() {
this.router.navigate(['/home/login']);
}
}
login.page.ts
validateInputs() {
const mobile = this.postData.mobile.trim();
const password = this.postData.password.trim();
return (
this.postData.mobile &&
this.postData.password &&
mobile.length > 0 &&
password.length > 0
);
}
formLogin() {
if (this.validateInputs()) {
this.loader.loadingPresent();
console.log(this.postData);
this.authService.login(this.postData).subscribe(
(res: any) => {
if (res.status === true) {
this.loader.loadingDismiss();
// Storing the User data.
this.storageService.store(AuthConstants.AUTH, res.logindata);
this.router.navigate(['/home/blog']);
} else {
this.loader.loadingDismiss();
this.toastService.presentToast(res.error);
}
},
(error: any) => {
this.loader.loadingDismiss();
this.toastService.presentToast('Network Issue.');
}
);
} else {
this.loader.loadingDismiss();
this.toastService.presentToast('Please enter mobile or password.');
}
}
StorageService.ts
import { Injectable } from '#angular/core';
import { Plugins } from '#capacitor/core';
const { Storage } = Plugins;
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
// Store the value
async store(storageKey: string, value: any) {
const encryptedValue = btoa(escape(JSON.stringify(value)));
await Storage.set({
key: storageKey,
value: encryptedValue
});
}
// Get the value
async get(storageKey: string) {
const ret = await Storage.get({ key: storageKey });
return JSON.parse(unescape(atob(ret.value)));
}
async removeStorageItem(storageKey: string) {
await Storage.remove({ key: storageKey });
}
// Clear storage
async clear() {
await Storage.clear();
}
}
You can also do that like this
in your html
<ion-menu-toggle auto-hide="false" >
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()" > Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
in your .ts
showBtnLogin: boolean = true;
currentUser: any;
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
// this.postData.user_id = res.id;
console.log(this.authUser.id);
this.currentUser = this.authUser;
if (res === null) {
this.showBtnLogin = true;
} else {
this.showBtnLogin = false;
}
});
}
logout() {
this.authService.logout();
}
login() {
this.router.navigate(['/home/login']);
}
Change some code in your .ts file here it is
showBtnLogin = true;
public appPages = [
{
title: 'Blog',
url: '/home/blog',
icon: 'home'
},
{
title: 'Profile',
url: '/home/profile',
icon: 'cog',
status: true
},
{
title: 'Change Password',
url: '/home/change-password',
icon: 'lock',
status: true
},
{
title: 'About Us',
url: '/home/about-us',
icon: 'cog',
status: true
},
{
title: 'Privacy Policy',
url: '/home/privacy-policy',
icon: 'settings',
status: true
}
,
{
title: 'Terms & Conditions',
url: '/home/terms-conditions',
icon: 'paper',
status: true
},
{
title: 'Enable Location',
url: '/home/enable-location',
icon: 'pin',
status: true
}
,
{
title: 'Donation',
url: '/home/donation',
icon: 'card',
status: true
}
];
In your ngOnInit
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
if (res === null) {
console.log(res);
this.showBtnLogin = false;
for (let i = 0; i < this.appPages.length; i++) {
if (this.appPages[i].title == 'Profile') {
this.appPages[i].status = false;
}
if (this.appPages[i].title == 'Change Password') {
this.appPages[i].status = false;
}
}
} else {
this.showBtnLogin = true;
}
});
}
if your profile and change password index not change then you can directly change status via index without using for loop
and finally in your logout
logout() {
this.authService.logout();
for (let i = 0; i < this.appPages.length; i++) {
if (this.appPages[i].title == 'Profile') {
this.appPages[i].status = false;
}
if (this.appPages[i].title == 'Change Password') {
this.appPages[i].status = false;
}
}
}
In your .html file
<ion-list>
<ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
<ion-item [routerDirection]="'root'" [routerLink]="[p.url]" *ngIf="p.status">
<ion-icon slot="start" [name]="p.icon"></ion-icon>
<ion-label>
{{p.title}}
</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false">
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()"> Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>

Ionic4 Ion-select style property not working

I would like to apply css property for my alert Controller but not working.
home.html
<ion-select [(ngModel)]="accountSystem" placeholder="Match Accounting Standard" okText="Done" cancelText="Cancel" class="select-account">
<ion-select-option value="PRC Gaap">PRC Gaap</ion-select-option>
<ion-select-option value="IFRS">IFRS</ion-select-option>
<ion-select-option value="US Gaap">US Gaap</ion-select-option>
</ion-select>
global.scss
.select-account{
.alert-wrapper{
.alert-button-inner{
color:rgb(239,52,52);
}
.alert-button{
color:rgb(52,223,57);
}
}}
this is my working solution in my project.
home.ts
const alert = await this.alertCtrl.create({
header: "Alert",
mode: "ios",
cssClass: "codealert",
buttons: [
{
text: 'Cancel',
role: 'cancel',
cssClass: 'alertbutton',
handler: () => {
console.log('Confirm Cancel');
}
}, {
text: 'Ok',
cssClass: 'alertbutton',
handler: () => {
console.log('Confirm Ok');
}
}
]
});
await alert.present();
}
global.scss
.codealert {
--background: white;
}
.alertbutton {
color: #600001 !important;
font-weight: bold;
}

How to add text-area and select to the Alert in Ionic

I am working on Ionic App and I want to show I am showing the input fields in the alert but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my popupdetails.ts file:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-checkout',
templateUrl: 'checkout.html',
})
export class CheckoutPage {
constructor(public navCtrl: NavController, public navParams: NavParams,
public loadingCtrl: LoadingController, private alertCtrl: AlertController) {
}
presentPrompt() {
let alert = this.alertCtrl.create({
title: 'Submit Shipping Details',
inputs: [
{
name: 'name',
placeholder: 'Name'
},
{
name: 'mobilenumber',
placeholder: 'Mobile Number',
type: 'number'
},
{
name: 'pincode',
placeholder: 'Pincode',
type: 'number'
},
{
name: 'state',
placeholder: 'State',
},
{
name: 'city',
placeholder: 'City',
},
{
name: 'address',
placeholder: 'Address',
},
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Submit',
handler: data => {
console.log('Submit clicked');
}
}
]
});
alert.present();
}
}
In this, I have used the alert controller to the input fields but the problem is that, I am not able to show the textarea and the select box in the alert controller.
This is my output currently coming.
I want this type of output with textarea and the select box.
Any help is much appreciated.
https://stackblitz.com/edit/ionic-x1os3c please check this link may hope it will help you
<ion-content padding style="background:white">
<ion-list no-lines>
<form>
<p style="font-weight:bold">Name</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='text'></ion-input>
</ion-item>
<p style="font-weight:bold">Mobile</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" type='tel'></ion-input>
</ion-item>
<p style="font-weight:bold">Country</p>
<ion-item>
<ion-label hidden></ion-label>
<ion-input style="border:1px solid black" readonly="true" type='text'></ion-input>
</ion-item>
</form>
<ion-grid>
<ion-row>
<ion-col>
<button color="secondary" ion-button float-right>Add</button>
<button color="light" ion-button float-right>Close</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
</ion-content>

How can I change an item in app.component.ts?

I am working on a project in Ionic, and when I login, I did set the storage('id') which was used in the app.component.ts to get the user details, but when I run the code, it didn't work, but when I reload the whole page (Ctrl + R), it then works.
Here is my code.
login.ts:
import {Component} from "#angular/core";
import {NavController, AlertController, ToastController, MenuController} from "ionic-angular";
import {HomePage} from "../home/home";
import {RegisterPage} from "../register/register";
import { ServicesProvider } from '../../providers/services/services';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
private user = {
email: '',
password: ''
}
private setputt:string;
constructor(public navCtrl: NavController,
public forgotCtrl: AlertController,
public menu: MenuController,
public toastCtrl: ToastController,
private storage: Storage,
public ServicesProvider: ServicesProvider
) {
this.menu.swipeEnable(false);
}
register() {
this.navCtrl.setRoot(RegisterPage);
}
login(user){
this.ServicesProvider.loginpost(user).subscribe(
data => {
if(data.success){
this.setputt = data.message;
if(this.setputt == 'Login Successfull'){
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
}
}
else{
this.setputt = data.message;
}
},
error => {
console.log(error);
}
)
}
// set a key/value
// storage.set('name', 'Max');
// // Or to get a key/value pair
// storage.get('age').then((val) => {
// console.log('Your age is', val);
// });
// storage.remove('name');
forgotPass() {
let forgot = this.forgotCtrl.create({
title: 'Forgot Password?',
message: "Enter you email address to send a reset link password.",
inputs: [
{
name: 'email',
placeholder: 'Email',
type: 'email'
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Send',
handler: data => {
console.log('Send clicked');
let toast = this.toastCtrl.create({
message: 'Email was sended successfully',
duration: 3000,
position: 'top',
cssClass: 'dark-trans',
closeButtonText: 'OK',
showCloseButton: true
});
toast.present();
}
}
]
});
forgot.present();
}
}
app.component.ts:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Storage } from '#ionic/storage';
import { ServicesProvider } from '../providers/services/services';
import { HomePage } from '../pages/home/home';
import {LoginPage} from "../pages/login/login";
import {ProfilePage} from "../pages/profile/profile";
import {FriendsPage} from "../pages/friends/friends";
import {YearbooksPage} from "../pages/yearbooks/yearbooks";
import {ChatPage} from "../pages/chat/chat";
import {FilesPage} from "../pages/files/files";
import {CheckLoginPage} from "../pages/check-login/check-login";
export interface MenuItem {
title: string;
component: any;
icon: string;
}
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = CheckLoginPage;
appMenuItems: Array<MenuItem>;
public FullNamer;
public pixr;
public id:number;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public storage: Storage,
public ServicesProvider: ServicesProvider
) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
});
this.storage.get('id').then((vals) => {
if (vals != null) {
this.ServicesProvider.getDetails(vals).subscribe(data=>{
// console.log(data);
this.pixr = this.ServicesProvider.theurl+data.pix;
this.FullNamer = data.fullname;
});
}
});
this.appMenuItems = [
{title: 'Home', component: HomePage, icon: 'home'},
{title: 'Files', component: FilesPage, icon: 'ios-folder'},
{title: 'Friends', component: FriendsPage, icon: 'ios-people'},
{title: 'Yearbooks', component: YearbooksPage, icon: 'ios-book'},
{title: 'Chat', component: ChatPage, icon: 'md-chatbubbles'}
];
}
ionViewCanEnter(){
}
openPage(page) {
this.nav.setRoot(page.component);
}
GoPages(){
this.nav.setRoot(ProfilePage);
}
logout() {
this.storage.remove('id');
this.storage.remove('FullName');
this.nav.setRoot(LoginPage);
}
}
app.html
<ion-menu side="left" id="authenticated" [content]="content">
<ion-header>
<ion-toolbar class="user-profile">
<ion-grid>
<ion-row>
<ion-col col-4>
<div class="user-avatar">
<img [src]="pixr">
</div>
</ion-col>
<ion-col padding-top col-8>
<h2 ion-text class="no-margin bold text-white">
{{FullNamer}}
</h2>
<span ion-text color="light">Customer</span>
</ion-col>
</ion-row>
<ion-row no-padding class="other-data">
<ion-col no-padding class="column">
<button ion-button icon-left small full class="round" color="light" menuClose (click)="GoPages()">
<ion-icon name="ios-person"></ion-icon>
Edit Profile
</button>
</ion-col>
<ion-col no-padding class="column">
<button ion-button icon-left class="round" small full color="light" menuClose (click)="logout()">
<ion-icon name="log-out"></ion-icon>
Log Out
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-toolbar>
</ion-header>
<ion-content color="primary">
<ion-list class="user-list">
<button ion-item menuClose class="text-1x" *ngFor="let menuItem of appMenuItems" (click)="openPage(menuItem)">
<ion-icon item-left [name]="menuItem.icon" color="primary"></ion-icon>
<span ion-text color="primary">{{menuItem.title}}</span>
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
service.ts:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
#Injectable()
export class ServicesProvider {
public theurl = 'http://localhost/HoleeSheet/php/';
public tittle = 'Holee Sheet';
public id:number;
constructor(public http: HttpClient, private storage: Storage) {
this.storage.get('id').then((valr) => {
if (valr != null) {
this.id = valr;
}
});
}
loginpost(user){
return this.http.put<obbbbs>(this.theurl+'login.php', {
email: user.email,
password: user.password
});
}
getDetails(humid){
console.log(humid);
return this.http.post<details>(this.theurl+'getDetails.php', {
id: humid
});
}
}
interface details{
'fullname': string,
'pix':string
}
interface obbbbs {
'success': 'boolean',
'message': 'string',
'id': 'string'
}
How can I solve this issue?
Welcome to Stack Overflow.
// LoginPage.login method (login.ts)
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
You're navigating to the home page before the value gets saved to storage. You should wait until the promise returned by this.storage.set is resolved before continuing navigation:
// LoginPage.login method (login.ts)
this.storage.set('id', data.id)
.then(() => this.navCtrl.setRoot(HomePage));

Print PDF in ionic 3

I am using PDFMake for creating the pdf with my predefined Document definition. In my old ionic 1 project, I am passing the encoded string to print function which works fine. here is the code for old ionic 1
var dd = $scope.createDocumentDefinition();
$timeout(function () {
var pdf = pdfMake.createPdf(dd);
pdf.getBase64(function (encodedString) {
console.log(encodedString);
$ionicLoading.hide();
window.plugins.PrintPDF.print({
data: encodedString,
type: 'Data',
title: 'Print Document',
success: function () {
console.log('success');
},
error: function (data) {
data = JSON.parse(data);
console.log('failed: ' + data.error);
}
});
});
}, 1000);
Now I am upgrading my project to Ionic 3 so I tried the same thing but the output is different here is my new ionic 3 code. printer open but instead of printing as per my document definition it just prints the encoded string.
let printer_ = this.printer;
var dd = this.createDocumentDefinition();
var pdf = pdfMake.createPdf(dd);
pdf.getBase64(function (_encodedString) {
let options: PrintOptions = {
name: 'MyDocument'
};
console.log(JSON.stringify(pdf));
printer_.print(_encodedString, options).then((msg)=>{
console.log("Success",msg);
},(error) => {
console.log("Error", error);
});
});
Any idea how to use this in ionic 3 ??
You can use pdfmake for generate PDF using ionic.
First you need to install plugin for file and file opener.
ionic cordova plugin add cordova-plugin-file-opener2
ionic cordova plugin add cordova-plugin-file
After that install NPM package of file, FileOpener and PDF make
npm install pdfmake
npm install #ionic-native/file-opener
npm install #ionic-native/file
Open your src/app.module.ts and include file and fileoperner reference:
import { File } from '#ionic-native/file';
import { FileOpener } from '#ionic-native/file-opener';
Add File and FileOpener in provider
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
File,
FileOpener
]
I am generating a template UI looks like this:
<ion-header>
<ion-navbar>
<ion-title>
Ionic PDF
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label stacked>From</ion-label>
<ion-input [(ngModel)]="letterObj.from"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>To</ion-label>
<ion-input [(ngModel)]="letterObj.to"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Text</ion-label>
<ion-textarea [(ngModel)]="letterObj.text" rows="10"></ion-textarea>
</ion-item>
<button ion-button full (click)="createPdf()">Create PDF</button>
<button ion-button full (click)="downloadPdf()" color="secondary" [disabled]="!pdfObj">Download PDF</button>
</ion-content>
After that your home.component.ts code looks like this:
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import { File } from '#ionic-native/file';
import { FileOpener } from '#ionic-native/file-opener';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
letterObj = {
to: '',
from: '',
text: ''
}
pdfObj = null;
constructor(public navCtrl: NavController, private plt: Platform, private file: File, private fileOpener: FileOpener) { }
createPdf() {
var docDefinition = {
content: [
{ text: 'REMINDER', style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'From', style: 'subheader' },
{ text: this.letterObj.from },
{ text: 'To', style: 'subheader' },
this.letterObj.to,
{ text: this.letterObj.text, style: 'story', margin: [0, 20, 0, 20] },
{
ul: [
'Bacon',
'Rips',
'BBQ',
]
}
],
styles: {
header: {
fontSize: 18,
bold: true,
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 15, 0, 0]
},
story: {
italic: true,
alignment: 'center',
width: '50%',
}
}
}
this.pdfObj = pdfMake.createPdf(docDefinition);
}
downloadPdf() {
if (this.plt.is('cordova')) {
this.pdfObj.getBuffer((buffer) => {
var blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
})
});
} else {
// On a browser simply use download!
this.pdfObj.download();
}
}
}