How to open a modal in ionic 5? - ionic-framework

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.

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 lazy load modals in ionic4

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

IONIC 3 - AdMob Free not Working even If isTesting is set true

I am trying from last 3 days to run Google AdMob in Ionic 3 application.
Steps I followed:
1. Created Ionic 3 App added AdMob Free.
2. To check if my AdMob account stopped ads, create a native android sample app of that banner ads started showing real-time. Real Ads, not Test.
3. Create a new Ionic 3 sample app but still no success.
Anyone facing similar issue?? please help Let me know if anything left which I forgot to follow.
I followed a tutorial given here
Here is my code:
Installed these packages:
cordova plugin add cordova-plugin-admob-free --save
npm install #ionic-native/admob-free --save
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { AdMobFree } from '#ionic-native/admob-free';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
AdMobFree,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { AdMobFree, AdMobFreeBannerConfig, AdMobFreeInterstitialConfig, AdMobFreeRewardVideoConfig } from '#ionic-native/admob-free';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,public admobFree: AdMobFree) {
}
showBannerAd() {
let bannerConfig: AdMobFreeBannerConfig = {
isTesting: true, // Remove in production
autoShow: true//,
//id: "ca-app-pub-3940256099942544/6300978111"
};
this.admobFree.banner.config(bannerConfig);
this.admobFree.banner.prepare().then(() => {
alert("bannerConfig");
}).catch(e => alert(e));
}
showInterstitialAds(){
let interstitialConfig: AdMobFreeInterstitialConfig = {
isTesting: true, // Remove in production
autoShow: true//,
//id: "ca-app-pub-3940256099942544/1033173712"
};
this.admobFree.interstitial.config(interstitialConfig);
this.admobFree.interstitial.prepare().then(() => {
alert("interstitialConfig");
}).catch(e => alert(e));
}
showRewardVideoAds(){
let RewardVideoConfig: AdMobFreeRewardVideoConfig = {
isTesting: true, // Remove in production
autoShow: true//,
//id: "ca-app-pub-3940256099942544/5224354917"
};
this.admobFree.rewardVideo.config(RewardVideoConfig);
this.admobFree.rewardVideo.prepare().then(() => {
alert("RewardVideoConfig");
}).catch(e => alert(e));
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the docs will be your guide.
</p>
<button ion-button (click)="showBannerAd()">showBannerAd</button>
<button ion-button (click)="showInterstitialAds()">showInterstitialAds</button>
<button ion-button (click)="showRewardVideoAds()">showRewardVideoAds</button>
</ion-content>
UPDATE: Finally!! Ads are showing. may be it takes 2-3 days. :)
just try this in the command line(put your app Id between ""):
cordova plugin add cordova-plugin-admob-free --save --variable ADMOB_APP_ID="YOUR_APP_ID"
example :
cordova plugin add cordova-plugin-admob-free --save --variable ADMOB_APP_ID="ca-app-pub-90001987983570300~8789081597"
make sure to test it in emulator only, else you will get plugin not installed error.

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]
})

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