How to lazy load modals in ionic4 - ionic-framework

I need some help with lazy loading of modals in ionic 4. I googled a lot but can't find an exact solution.
I have several modals on a page. And I want to lazy load them. Following is the example of two modals on a page
In one of my modal, I need AndroidPermissions, so I have to import it in the module file of the page because importing in the module file of the modal is not working.
Why this is happening? Can ionic modals not be lazy-loaded?
Thank you in advance
home.module.ts
import { AddressPage } from '../pages/address/address.page'; // modal 1
import { AddAddressPage } from '../pages/add-address/add-address.page' // modal 2
import { AndroidPermissions } from '#ionic-native/android-permissions/ngx';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild([
{
path: '',
component: HomePage
}
])
],
declarations: [HomePage, AddressPage, AddAddressPage],
entryComponents :[AddressPage , AddAddressPage],
providers :[AndroidPermissions]
})
export class HomePageModule {}

To lazy loading of modals follow following steps
Add modal page's module in the import of your page
Remove all routing of modal as we don't need it
Remove modal's entry from app.routing.module
Add modal page in entryComponents of modal's module
In my case, I had two modals. The second modal is opened inside the first modal.
So I have to add modale1module in the import of the page and modal2module in the import of modal1module
base page.module
import { AddressModalPageModule } from '../address-modal/address-modal.module';
const routes: Routes = [
{
path: '',
component: CartsPage
}
];
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
RouterModule.forChild(routes),
ReactiveFormsModule,
AddressModalPageModule
],
declarations: [CartsPage ],
})
export class CartsPageModule {}
modal1.module
import { AddressModalPage } from './address-modal.page';
import { AddAddressModalPageModule } from '../add-address-modal/add-address-modal.module';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
AddAddressModalPageModule
],
declarations: [AddressModalPage],
entryComponents:[AddressModalPage]
})
export class AddressModalPageModule {}
modal2.module
import { AddAddressModalPage } from './add-address-modal.page';
import { AndroidPermissions } from '#ionic-native/android-permissions/ngx';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule
],
declarations: [AddAddressModalPage],
entryComponents:[AddAddressModalPage],
providers :[
AndroidPermissions, ]
})
export class AddAddressModalPageModule {}

Ionic 4 supports lazy loading for modals, but as the documentation says with nuance:
it's important to note that the modal will not be loaded when it is opened, but rather when the module that imports the modal's module is loaded
To lazy load a modal you need to:
import your modal page module into the module of a component from which
the modal page will be opened
ensure you added the modal page into entry components list of the modal page module
You should be able to access your singleton provider inside your modal, by just importing it into the modal's page (Angular 8)
for example your modal's module ts looks like this:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
// import the component for your modal's content:
import { MyModalComponent } from '../my-modal/my-modal.component'
#NgModule({
// add it to entry components and to the declarations:
entryComponents: [MyModalComponent],
declarations: [MyModalComponent],
imports: [
CommonModule
]
})
export class LazyLoadedModalModule { }
Then importing it into the module of the page that will call the modal would look like this:
...
// import lazy loaded module:
import { LazyLoadedModalModule } from '../lazy-loaded-modal/lazy-loaded-modal.module';
#NgModule({
imports: [
IonicModule,
CommonModule,
// add it to the imports:
LazyLoadedModalModule,
RouterModule.forChild([{ path: '', component: Tab1Page }])
],
declarations: [Tab1Page]
})
export class Tab1PageModule {}
now in the page where you need to create the modal you need to import the component and use modal controller:
import { Component } from '#angular/core';
import { ModalController } from '#ionic/angular';
import { MyModalComponent } from '../my-modal/my-modal.component'
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
constructor(private modalCtrl: ModalController) {}
async openModal() {
const modal = await this.modalCtrl.create({
component: MyModalComponent
});
await modal.present();
}
}

Related

Add Components dynamically in DOM ionic+angular

I am following How to Dynamically Create a Component in Angular to add components dynamically inside another component. I am receiving a weired error of undefined variable.
My Component file (MessComponent)
<template #messContainer>
<p>
mess works!
</p>
</template>
ts file
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-mess',
templateUrl: './mess.component.html',
styleUrls: ['./mess.component.scss'],
})
export class MessComponent implements OnInit {
constructor() { }
ngOnInit() {}
}
Parent Component (hosting dynamic component)
module ts file
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { CommonModule } from '#angular/common';
import { IonicModule } from '#ionic/angular';
import { FormsModule } from '#angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';
import { MessComponent } from './../mess/mess.component';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HomePageRoutingModule
],
declarations: [HomePage, MessComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
entryComponents: [MessComponent]
})
export class HomePageModule {}
ts file
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory, OnInit } from "#angular/core";
import { MessComponent } from "./../mess/mess.component";
#Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"],
})
export class HomePage implements OnInit {
componentRef: any;
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;
createComponent() {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(MessComponent);
this.componentRef = this.entry.createComponent(factory);
}
destroyComponent() {
this.componentRef.destroy();
}
constructor(private resolver: ComponentFactoryResolver) {}
ngOnInit(): void {
this.createComponent();
}
}
and the error I am receiving
Uncaught (in promise): TypeError: this.entry is undefined
I understand this is claiming regarding the variable entry, but don't understand why it is not identifying that variable. To conclude, why I cannot add the component?
Solved it. Actually I was passing wrong param to the #ViewChild(''). I was passing the template name (container) of the child while I should have passed the container name in the parent component. So created a div in the parent component with #messContainer and corrected the #ViewChild
Important!:
now #messContainer is in the parent component and everything works as expected.
#ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;

How to open a modal in ionic 5?

I want to open a modal in ionic 5. But somehow I can't find the component.module.ts file where I can export the modals/componets that I want to use. Did they change that system, how is it done with ionic 5? Do you know a piece of documentation for that? The whole system seems to have changed like there is always a page-routing.module.ts. in every page file.
There is nothing new changes for opening modal.
Add modalPage or modalComponent to app.module.ts [ Or Home.module.ts if lazy-loaded ] in entryComponents and declarations
app.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { IonicModule } from '#ionic/angular';
import { FolderPageRoutingModule } from './folder-routing.module';
import { FolderPage } from './folder.page'; //from where you open
import { ModalPage } from '../modal/modal.page';
#NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
FolderPageRoutingModule
],
declarations: [ModalPage],
entryComponents: [ModalPage] //modal page
})
export class FolderPageModule {}
and open you modal from corresponding page.
async presentModal() {
const modal = await this.modalController.create({
component: ModelComponent,
componentProps: { value: 123 }
});
await modal.present();
}
Hope this help.

No Provider for AuthHttp! Angular2-Jwt provider issue

At least I thought I was providing correctly. Below are the relevant snippets of my app.module file and the service in which I use AuthHttp. I followed the configuration in the ReadMe for creating the factory method to provide for AuthHttp, but there is a persisting issue with it not being recognized in my service. I've read the literature on nested dependency injections, and I feel as though I'm doing things correctly.
app.module.ts
import { Http, RequestOptions } from '#angular/http';
import { provideAuth, AuthHttp, AuthConfig } from 'angular2-jwt/angular2-jwt';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig(), http, options);
}
#NgModule({
declarations: [
AppComponent,
ButtonFormComponent,
...
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule,
AppRoutingModule
],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
},
employee.service.ts
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { ApiSettings } from './api-settings';
#Injectable()
export class EmployeeService {
api: String;
auth: String;
constructor(private http: Http, private authHttp: AuthHttp) {
this.api = ApiSettings.API;
this.auth = ApiSettings.Auth;
}
You can get rid of this issue by just using following import in your app.module.ts, here the key import for you is, AUTH_PROVIDERS.
Also, make sure you include AUTH_PROVIDERS in the providers array.
import { AuthHttp, AUTH_PROVIDERS, provideAuth, AuthConfig } from
'angular2-jwt/angular2-jwt';
#NgModule({
providers: [AUTH_PROVIDERS]
})

Accordion List within ionic 2

I've create a custom components named Accordion within iconic 2 and working in browser perfectly but on device not working.
I've split my code up into components, where
Home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {DataCards} from '../../components/data-cards/data-cards';
import {Data} from '../../components/data/data';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public dataList: Data[];
constructor(public navCtrl: NavController) {
this.dataList = [
new Data('title 1', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ','ios-remove-circle-outline', true),
new Data('title 2', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ','ios-add-circle-outline', false),
new Data('title 3', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ','ios-add-circle-outline', false)
];
}
}
and the corresponding HTML
<ion-content padding>
<data-cards [data]="dataList"></data-cards>
</ion-content>
contain my custom component data-cards. data-cards has an input parameter data, through which the list of data is passed.
data.ts
import { Component } from '#angular/core';
#Component({
selector: 'data',
templateUrl: 'data.html'
})
export class Data {
constructor(public title: string, public details: string, public icon: string, public showDetails: boolean) {}
}
data-cards.ts
import { Component } from '#angular/core';
import { Data } from '../data/data';
#Component({
selector: 'data-cards',
inputs: ['data'],
templateUrl: 'data-cards.html'
})
export class DataCards {
public data: Data[];
constructor() {}
toggleDetails(data: Data) {
if (data.showDetails) {
data.showDetails = false;
data.icon = 'ios-add-circle-outline';
} else {
data.showDetails = true;
data.icon = 'ios-remove-circle-outline';
}
}
}
app.module.ts
import { NgModule } from '#angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { Data } from '../components/data/data';
import { DataCards } from '../components/data-cards/data-cards';
#NgModule({
declarations: [
MyApp,
HomePage,
Data,
DataCards
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
Data,
DataCards
],
providers: []
})
export class AppModule {}
When run on iOS ( ionic run ios ) i've got an error like below :
[08:44:54] Error: Error at /Users/imac/Documents/ionic2Accordion/.tmp/components/data/data.ngfactory.ts:29:71
[08:44:54] Property 'string' does not exist on type 'typeof "/path/ionic2Accordion/.tmp/components/data/data"'.
[08:44:54] Error at /path/ionic2Accordion/.tmp/components/data/data.ngfactory.ts:29:111
[08:44:54] Property 'string' does not exist on type 'typeof "/path/ionic2Accordion/.tmp/components/data/data"'.
[08:44:54] Error at /path/ionic2Accordion/.tmp/components/data/data.ngfactory.ts:29:151
[08:44:54] Property 'string' does not exist on type 'typeof "/path/ionic2Accordion/.tmp/components/data/data"'.
[08:44:54] Error at /path/ionic2Accordion/.tmp/components/data/data.ngfactory.ts:29:191
[08:44:54] Property 'boolean' does not exist on type 'typeof "/path/ionic2Accordion/.tmp/components/data/data"'.
[08:44:54] ngc failed
[08:44:54] ionic-app-script task: "build"
[08:44:54] Error: Error
so my question : how i can resolve this problem any suggestion ?
In data-card.ts change
public data: Data[];
o be
Input() data: Data[];
since you will be assigning it from the component creation in the home.html? You'll also need to import the Input module via
import { Component, Input } from '#angular/core';

what is wrong in my storage implementation ionic 2 app?

i'm trying to save data in local storage in ionic 2 app so i
import the storage and did exactly like i saw in the website and it not save the data in the storage
import { Component} from '#angular/core';
import { NavController,NavParams,LoadingController,AlertController,ViewController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
//import pages
import {LoginPage} from "../../pages/login/login";
import {User} from '../../models/user'
import { Storage} from '#ionic/storage';
//import provider
import { ProfileData } from '../../providers/profile-data';
import { NotesData } from '../../providers/notes-data';
import firebase from 'firebase'
import {AddNote} from "../add-note/add-note";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
pages: Array<{title: string, component: any}>;
photo:any;
constructor(public navCtrl: NavController,public storage:Storage) {
}
ionViewDidLoad() {
this.getDetailsFacebook();
}
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
that.uid = response.id;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.storage.set('photo',that.photo');
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
photo of the inspect with chrome developer
i don't see any key of photo as i set it.. why is that?
Installation
To use this in your Ionic 2/Angular 2 apps, either start a fresh Ionic project which has it installed by default, or run:
npm install #ionic/storage
If you'd like to use SQLite as a storage engine, install a SQLite plugin (only works while running in a simulator or on device):
cordova plugin add cordova-sqlite-storage --save
In order to use Storage you may have to edit your NgModule declaration in src/app/app.module.ts to add Storage as a provider as below:
import { Storage } from '#ionic/storage';
#NgModule({
declarations: [
...
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
...
],
providers: [ Storage ] // Add Storage as a provider
})
export class AppModule {}
Now, you can easily inject Storage into a component:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public storage: Storage) {
}
}
To set an item, use Storage.set(key, value):
this.storage.set('name', 'Mr. Ionitron');
To get the item back, use Storage.get(name).then((value) => {}) since get() returns a Promise:
this.storage.get('name').then((name) => {
console.log('Me: Hey, ' + name + '! You have a very nice name.');
console.log('You: Thanks! I got it for my birthday.');
});
For more info on Storage module refer link: https://github.com/driftyco/ionic-storage