Add Components dynamically in DOM ionic+angular - ionic-framework

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;

Related

How to creat a dynamic text

I have a list of titles, and I would like these texts to alternate as I switch to ion-select. How do I do this?
I have no idea how to do this, not even what part of the code to show. I made an attempt here but whenever I use the console the value returned is undefined.
My typescrit code:
import { Titulo } from './../Services/services.service';
import { DataService } from './data.service';
import { Component, OnInit, ViewChild} from '#angular/core';
import {IonSlides} from '#ionic/angular';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-libertacao',
templateUrl: './libertacao.page.html',
styleUrls: ['./libertacao.page.scss'],
})
export class LibertacaoPage implements OnInit {
#ViewChild(IonSlides) slides: IonSlides;
PAGINA_SELECIONADA: number;
// tslint:disable-next-line: variable-name
index_atual: number;
titulo: Titulo;
constructor(private dataservice: DataService, private activatedRoute: ActivatedRoute ){
}
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.titulo = this.dataservice.getTituloById(parseInt(id, 10));
}
OnChange(event: any)
{
if (event.detail.value === this.PAGINA_SELECIONADA) {
this.slides.slideTo(this.PAGINA_SELECIONADA);
}
else {}
console.log(this.titulo);
}
slideChanged() {
this.slides.getActiveIndex().then((index) => {
this.index_atual = index;
});
}
}

Fix the TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'

I'm trying to setup Google Maps Places Autocomplete in an new Ionic app.
here is the problem. On the first search, I got this error in the console:
TypeError: Cannot read property 'place_id' of undefined
and this error in the terminal:
TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'HTMLInputElement'
However, on the second search I get the place_id without any error.
Here is my (simplified) .ts file
import { Component, OnInit } from '#angular/core';
import { google } from "google-maps";
import { Platform } from '#ionic/angular';
#Component({...})
export class AddaddressPage implements OnInit {
autocomplete:any;
constructor(public platform: Platform) {}
ngOnInit() {
this.platform.ready().then(() => {
this.autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
this.autocomplete.setFields(['place_id']);
});
}
fillInAddress() {
var place = this.autocomplete.getPlace();
console.log(place);
console.log(place.place_id);
}
}
and the input I use:
<input id="autocomplete" type="text" (change)="fillInAddress()" />
How should I proceed ?
After playing around, here is the trick! ViewChild and Ion-input are needed.
.html
<ion-input #autocomplete type="text"></ion-input>
.ts
import { Component, OnInit, ViewChild } from '#angular/core';
import { google } from "google-maps";
import { Platform } from '#ionic/angular';
#Component(...)
export class AddaddressPage implements OnInit {
googleAutocomplete:any;
#ViewChild('autocomplete') autocompleteInput: ElementRef;
constructor(public platform: Platform) { }
ngOnInit() {
this.platform.ready().then(() => {
this.autocompleteInput.getInputElement().then((el)=>{
this.googleAutocomplete = new google.maps.places.Autocomplete(el);
this.googleAutocomplete.setFields(['place_id']);
this.googleAutocomplete.addListener('place_changed', () => {
var place = this.googleAutocomplete.getPlace();
console.log(place);
console.log(place.place_id);
});
})
});
}
}

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

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