When navigating to other page keep showing the navtabs - angular6

I am migrating my application from ionic 3 to ionic 4 and I am wondering how to keep showing the navtabs when navigating between pages. When I do this:
[routerLink]="'/offers/'" routerDirection="forward"
The tabs disappear, what do I have to do when I almost always want to show the navtabs?
Define the routes in tabs.router.module.ts or in the pages?
Hope somebody could help me out on this.

Something like this is doing it for me. So basically yes, define the routes in your router's routing module.
app.module.ts
import { NgModule } from '#angular/core';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
IonicModule.forRoot(),
AppRoutingModule,
],
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
],
bootstrap: [AppComponent],
})
export class AppModule {
}
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'start/tabs', pathMatch: 'full' },
{ path: 'start', loadChildren: './pages/tabs/tabs.module#TabsModule' },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
tabs.module.ts
import { CommonModule } from '#angular/common';
import { NgModule } from '#angular/core';
import { IonicModule } from '#ionic/angular';
import { PageAPageModule } from '../pageA/PageA.module';
import { PageBPageModule } from '../pageB/PageB.module';
import { TabsPage } from './tabs.page';
import { TabsPageRoutingModule } from './tabs.page-routing.module';
#NgModule({
imports: [
CommonModule,
IonicModule,
PageAPageModule,
PageBPageModule,
TabsPageRoutingModule,
],
declarations: [
TabsPage,
],
})
export class TabsModule {
}
tabs.page-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { PageAPage } from '../pageA/pageA.page';
import { TabsPage } from './tabs.page';
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'pageA',
children: [
{ path: '', component: PageAPage },
{ path: 'subPageA1', loadChildren: '../subPageA1/subPageA1.module#SubPageA1PageModule' },
{ path: 'subPageA2', loadChildren: '../subPageA2/subPageA2.module#SubPageA2PageModule' },
],
},
{
path: 'pageB',
children: [
{ path: '', loadChildren: '../pageB/pageB.module#PageBPageModule' },
{ path: ':id', loadChildren: '../pageB-detail/pageB-detail.module#PageBDetailModule' },
],
},
{
path: 'pageX',
...
},
{
path: '', redirectTo: '/start/tabs/pageA', pathMatch: 'full',
},
],
},
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class TabsPageRoutingModule {
}
tabs.page.html
<ion-tabs>
<ion-tab-bar color="dark" slot="bottom">
<ion-tab-button tab="pageA">
<ion-icon name="calendar"></ion-icon>
<ion-label>pageA</ion-label>
</ion-tab-button>
<ion-tab-button tab="pageB">
<ion-icon name="contacts"></ion-icon>
<ion-label>pageB</ion-label>
</ion-tab-button>
<ion-tab-button tab="pageX">
<ion-icon name="contacts"></ion-icon>
<ion-label>pageX</ion-label>
</ion-tab-button>
</ion-tab-bar>
</ion-tabs>
app.component.html
<ion-list>
<ion-menu-toggle auto-hide="false">
<ion-item routerLink="/start/tabs/pageA">
<ion-icon slot="start" name="person"></ion-icon>
<ion-label>pageA</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false">
<ion-item routerLink="/start/tabs/pageA/subPageA1">
<ion-icon slot="start" name="person"></ion-icon>
<ion-label>subPageA1</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false">
<ion-item routerLink="/start/tabs/pageB">
<ion-icon slot="start" name="person"></ion-icon>
<ion-label>pageB</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false">
<ion-item routerLink="/start/tabs/pageX">
<ion-icon slot="start" name="person"></ion-icon>
<ion-label>pageX</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>

Related

I can't connect my ionic app with a mysql database

In a project that I have to do I was copying some lines from a youtube project, trying to connect the login page to a mysql database. All the project is in a htdocs folder of xampp, also there is a server_api folder with a config.php (I describe its content below) and a file_aski.php (with nothing in it). Please any help would be great! Thanks.
The files that I describe below are:
config.php
app.module.ts
app.component.ts
app-routing.module.ts
login.page.ts
login.page.html
---------- config.php ----------
<?php
// setting config database
define('DB_NAME', 'dbtotalinspector');
define('DB_USER', 'root');
define('DB_PASSWORD', ''); // default
define('DB_HOST', 'localhost'); // default xampp
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
?>
---------- app.module.ts ----------
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
/* import { HttpModule } from '#angular/http';
import { PostProvider } from '../providers/post-provider';
import { IonicStorageModule } from '#ionic/storage-angular';
*/
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule /* , IonicStorageModule.forRoot(), PostProvider*/],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy } /*, PostProvider */ ],
bootstrap: [AppComponent],
})
export class AppModule {}
---------- app.component.ts ----------
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
constructor() {}
}
---------- app-routing.module.ts ----------
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
},
{
path: 'seleccionar-obra',
loadChildren: () => import('./seleccionar-obra/seleccionar-obra.module').then( m => m.SeleccionarObraPageModule)
},
{
path: 'cargar-obra',
loadChildren: () => import('./cargar-obra/cargar-obra.module').then( m => m.CargarObraPageModule)
},
{
path: 'cargar-item',
loadChildren: () => import('./cargar-item/cargar-item.module').then( m => m.CargarItemPageModule)
},
{
path: 'desplegar-items-de-obra',
loadChildren: () => import('./desplegar-items-de-obra/desplegar-items-de-obra.module').then( m => m.DesplegarItemsDeObraPageModule)
},
{
path: 'tomar-fotografia',
loadChildren: () => import('./tomar-fotografia/tomar-fotografia.module').then( m => m.TomarFotografiaPageModule)
},
{
path: 'generar-informe',
loadChildren: () => import('./generar-informe/generar-informe.module').then( m => m.GenerarInformePageModule)
},
{
path: 'confirmar-enviar-informe',
loadChildren: () => import('./confirmar-enviar-informe/confirmar-enviar-informe.module').then( m => m.ConfirmarEnviarInformePageModule)
},
{
path: 'desplegar-foto',
loadChildren: () => import('./desplegar-foto/desplegar-foto.module').then( m => m.DesplegarFotoPageModule)
},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
---------- login.page.ts ----------
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
btnClickIngresar(){
this.router.navigateByUrl('/home');
}
}
---------- login.page.html ----------
<app-header></app-header>
<ion-content>
<div class="container">
<ion-card>
<ion-card-header>
<ion-card-title>Iniciar sesión</ion-card-title>
</ion-card-header>
<ion-card-content>
<ion-item>
<ion-icon name="person-outline" slot="start"></ion-icon>
<ion-item>
<ion-label position="floating">Usuario</ion-label>
<ion-input></ion-input>
</ion-item>
</ion-item>
<ion-item>
<ion-icon name="lock-open-outline" slot="start"></ion-icon>
<ion-item>
<ion-label position="floating">Contraseña</ion-label>
<ion-input type="password"></ion-input>
</ion-item>
</ion-item>
<ion-button expand="full" (click)="btnClickIngresar();">INGRESAR</ion-button>
</ion-card-content>
</ion-card>
</div>
</ion-content>
Thanks for all the advices, I'm reading the guidelines. Ok, I see that I have to cut the code to the most importan parts. As I see, the main problem is in "post-providers.ts" and maybe in in "app.module.ts" too. I took out the code between /* */ I will show you how the code looks and the error messages.
post-providers.ts
// providers api
import { Injectable } from "#angular/core";
import { Http,Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class PostProvider {
server: string = "http://localhost/server_api";
constructor (public http: Http){
}
postData(body, file){
let type = "application/json; charset=UTF-8";
let headers = new Headers({ 'Content-Type': type });
let options = new RequestOptions ({ headers: headers });
return this.http.post(this.server + file, JSON.stringify(body), options)
.map(res => res.json());
}
}
NOTE: on ".map" of the code above it says "Property 'map' does not exist on type 'Observable'.ts(2339)"
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpModule } from '#angular/http';
import { PostProvider } from '../providers/post-provider';
import { IonicStorageModule } from '#ionic/storage-angular';
#NgModule({
declarations: [AppComponent],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, IonicStorageModule.forRoot(), PostProvider, HttpModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, PostProvider ],
bootstrap: [AppComponent],
})
export class AppModule {}
NOTE: in app.module.ts, the "HttpModule" is cross out (or strike out) in both, "import {}" and the imports inside #NgModule of
The site appears in blank and it is compiled succesfully. But I don't see the login page.
THE ERRORS ARE:
./node_modules/rxjs/add/operator/map.js:7:0-39 - Error: Module not found: Error: Can't resolve 'rxjs-compat/add/operator/map' in 'C:\xampp\htdocs\totalinspector\node_modules\rxjs\add\operator'
[ng]
[ng] Error: src/providers/post-provider.ts:21:10 - error TS2339: Property 'map' does not exist on type 'Observable<Response>'.
[ng]
[ng] 21 .map(res => res.json());
[ng] ~~~
[ng] × Failed to compile.

How to add multiple routes in angular 9

I have a project on angular 9. where i want execute Three components in my homepage named header, body, and footer. and i have other two componets login and signup. These are working fine but homepage components are not working. Only header component is loading, others are not. I have found similar questions but they are not solving my problem
what i have tried
app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './component/login/login.component';
import { SignupComponent } from './component/signup/signup.component';
import { HeaderComponent } from './component/header/header.component';
import { BodyComponent } from './component/body/body.component';
import { FooterComponent } from './component/footer/footer.component';
const routes: Routes = [
{
path: '' , redirectTo: 'header,body,footer', pathMatch: 'full'
},
{
path: 'header', component:HeaderComponent
},
{
path: 'body' , component:BodyComponent
},
{
path: 'footer', component:FooterComponent
},
{
path: 'login', component:LoginComponent
},
{
path: 'signup' , component:SignupComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<router-outlet></router-outlet>
Thankyou
you need to create one common component called home component and include header,body,footer into that
home.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
route
{
path: 'home', component:HomeComponent
},
{
path: '' , redirectTo: 'home', pathMatch: 'full'
},

Ionic 4 tabs navigation pulls content to bottom

I'm developping an Hybrid App with IONIC 4.
The first page is a login (left) the second the home once authenticated (right):
As you can see the content for each tab is hidden on the bottom and only the component header is shown.
Here is some code:
Home routes
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: 'tabs',
component: HomePage,
children: [
{
path: 'newsfeed',
outlet: 'newsfeed',
loadChildren: '../news-feed/news-feed.module#NewsFeedPageModule'
},
{
path: 'sitters',
outlet: 'sitters',
loadChildren: '../sitters/sitters.module#SittersPageModule'
},
{
path: 'userprofile',
outlet: 'userprofile',
loadChildren: '../user-profile/user-profile.module#UserProfilePageModule'
}
]
},
{
path: '',
redirectTo: '/home/tabs/(newsfeed:newsfeed)'
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomePageRoutingModule { }
Homepage router outlet and tabs
<ion-tabs color="warning" useRouter="true">
<ion-tab label="Feed" icon="paw" href="/home/tabs/(newsfeed:newsfeed)">
<ion-router-outlet stack name="newsfeed"></ion-router-outlet>
</ion-tab>
<ion-tab label="Sitters" icon="people" href="/home/tabs/(sitters:sitters)">
<ion-router-outlet stack name="sitters"></ion-router-outlet>
</ion-tab>
<ion-tab label="Profile" icon="person" href="/home/tabs/(userprofile:userprofile)">
<ion-router-outlet stack name="userprofile"></ion-router-outlet>
</ion-tab>
</ion-tabs>
Each tab component has somethig like
<ion-header>
<ion-toolbar>
<ion-title>news-feed</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<p>Hello there.</p>
</ion-item>
</ion-list>
</ion-content>
But the content is always on the bottom. Any ideas? Thanks in advance warriors
I just encounter the same issue. And i spent almost 4 days trying to figure it out !
This is because of lazy loading. So you must do that :
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import NewsfeedPage from '../news-feed/news-feed.page';
import SittersPage from '../sitters/sitters.page';
import UserProfilePage from '../user-profile/user-profile.page';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: 'tabs',
component: HomePage,
children: [
{
path: 'newsfeed',
outlet: 'newsfeed',
component: NewsFeedPage
},
{
path: 'sitters',
outlet: 'sitters',
component: SittersPage
},
{
path: 'userprofile',
outlet: 'userprofile',
loadChildren: UserProfilePage
}
]
},
{
path: '',
redirectTo: '/home/tabs/(newsfeed:newsfeed)'
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomePageRoutingModule { }
Don't forget to import the modules in your home.module.ts
Hope it will help.

ngx-translation issue with ionic 3 app

ngx translation with ionic 3 app not working for me. below is my code:
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { HttpModule,Http } from '#angular/http';
import { IonicStorageModule } from '#ionic/storage';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { MyApp } from './app.component';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
export function createTranslateLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
declarations: [
MyApp
],
imports: [
BrowserModule,
HttpModule,
IonicStorageModule.forRoot(),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
}),
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {}
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Storage } from '#ionic/storage';
import { TranslateService } from '#ngx-translate/core';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
public rootPage: any;
constructor(public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
public storage: Storage,
public translate: TranslateService) {
this.storage.get('AppLangcode')
.then((AppLangcode) => {
if(AppLangcode==null){
translate.setDefaultLang('en');
}else{
translate.setDefaultLang(AppLangcode);
}
})
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.menu.swipeEnable(false);
});
}
}
In above file i am checking storage preference in local db and then set it to default language on load application.
My RootPage home.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
declarations: [
HomePage,
],
imports: [
IonicPageModule.forChild(HomePage),
TranslateModule.forChild()
],
exports: [
HomePage
]
})
export class HomePageModule {}
home.ts
import { Component} from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Storage } from '#ionic/storage';
import { TranslateService } from '#ngx-translate/core';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public navParams: NavParams,
public storage: Storage,
public translate: TranslateService,) {
}
ionViewDidLoad() {
//console.log('ionViewDidLoad HomePagePage');
}
}
home.html
<ion-header>
<ion-navbar color='navbarColor'>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
</ion-navbar>
</ion-header>
<ion-content class="grid-basic-page">
<ion-grid>
<ion-row>
<ion-col (click)="openPage('QuickBookPage');">
<div><img src="assets/icon/icon-book-cylinder.png">{{"quick_book_pay" | translate}}</div>
</ion-col>
<ion-col (click)="openPage('RefilHistoryPage');">
<div><img src="assets/icon/icon-quickpay.png">{{"refil_history" | translate}}</div>
</ion-col>
</ion-row>
<ion-row>
<ion-col (click)="openPage('ServicesPage');">
<div><img src="assets/icon/icon-mechanic.png">{{"service_request" | translate}}</div>
</ion-col>
<ion-col>
<button [disabled]="!clickhandle" (click)="emergencyCall();"><img src="assets/icon/icon-emergency.png">{{"emergency_helpline" | translate}}</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Side Menu Page language.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams,Events } from 'ionic-angular';
import { NgForm,FormBuilder, FormGroup, Validators } from '#angular/forms';
import { TranslateService } from '#ngx-translate/core';
import { Storage } from '#ionic/storage';
#IonicPage()
#Component({
selector: 'page-language',
templateUrl: 'language.html',
})
export class LanguagePage {
public langform:FormGroup;
public langcod:string;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public formBuilder: FormBuilder,
public translate: TranslateService,
public storage: Storage) {
this.storage.get('AppLangcode')
.then((AppLangcode) => {
if(AppLangcode==null){
this.langcod = 'en';
this.langform.get('langcode').setValue(this.langcod);
}else{
this.langcod = AppLangcode;
this.langform.get('langcode').setValue(this.langcod);
}
})
this.langform = formBuilder.group({
langcode: [this.langcod, Validators.required]
});
}
langselect(form: NgForm){
let langselcode = this.langform.value.langcode;
this.storage.set('AppLangcode', langselcode);
this.translate.setDefaultLang(langselcode);
this.translate.use(langselcode);
}
}
language.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule } from '#ngx-translate/core';
#NgModule({
declarations: [
LanguagePage,
],
imports: [
IonicPageModule.forChild(LanguagePage),
TranslateModule.forChild()
],
exports: [
LanguagePage
]
})
export class LanguagePageModule {}
language.html
<ion-header>
<ion-navbar color='navbarColor'>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title><img src="assets/icon/logo.png" alt="Ionic logo"></ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="langform" (submit)="langselect($event)">
<ion-list radio-group formControlName="langcode">
<ion-row responsive-sm>
<ion-col col-6>
<ion-item>
<ion-label>{{"english" | translate}}</ion-label>
<ion-radio value="en" checked></ion-radio>
</ion-item>
<ion-item>
<ion-label>{{"hindi" | translate}}</ion-label>
<ion-radio value="hi"></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</ion-list>
<ion-row responsive-sm>
<ion-col>
<button ion-button block type="submit" [disabled]="!langform.valid">
Submit
</button>
</ion-col>
</ion-row>
</form>
</ion-content>
en.json
{
"english" : "English",
"hindi" : "हिंदी",
"quick_book_pay":"Quick Book & Pay",
"refil_history":"Refill History",
"service_request":"Service Request",
"emergency_helpline":"Emergency Helpline"
}
hi.json
{
"english" : "English",
"hindi" : "हिंदी",
"quick_book_pay":"त्वरित बुक और भुगतान करें",
"refil_history":"रीफिल इतिहास",
"service_request":"सेवा अनुरोध",
"emergency_helpline":"आपातकालीन हेल्पलाइन"
}
On change language it show keys instead translation. Please let me know what wrong i am doing ?
i have updated my language module and this worked for me, not sure if this is right way but it's worked.
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LanguagePage } from './language';
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpModule,Http } from '#angular/http';
export function createTranslateLoader(http: Http) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
declarations: [
LanguagePage,
],
imports: [
IonicPageModule.forChild(LanguagePage),
TranslateModule.forChild({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [Http]
}
})
],
exports: [
LanguagePage
]
})
export class LanguagePageModule {}
i have added loader for child and export TranslateHttpLoader in language.module.ts
language.ts
langselect(form: NgForm){
let langselcode = this.langform.value.langcode;
this.storage.set('AppLangcode', langselcode);
this.translate.use(langselcode);
}
I spent hours to get it working on Ionic 3. Finally I had to add HttpClientModule to the import section of app.module.ts. Hope that helps.
[2]: Use HttpClient instead of Http
[3]: Add HttpClientModule
[4]: Use HttpClient instead of Http
src/app/app.module.ts:
import {HttpClient, HttpClientModule} from "#angular/common/http";
import {HttpModule, RequestOptions, XHRBackend} from '#angular/http';
import {TranslateModule, TranslateLoader} from '#ngx-translate/core';
import {TranslateHttpLoader} from '#ngx-translate/http-loader';
export function createTranslateLoader(http: HttpClient [2]) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
#NgModule({
...
imports: [
BrowserModule,
HttpModule,
HttpClientModule [2],
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient] [3]
}
...
...
}),
src/pages/[your-page]/[your-page].module.ts
imports: [
IonicPageModule.forChild(LoginPage),
TranslateModule.forChild(),
],
I had the same issue and managed to fix it. I'm lazy loading the pages and the problem occurred when I try to change the language from a component. He's how I fixed it.
app.component.ts
this.translateService.addLangs(['en', 'lk']);
this.translateService.setDefaultLang("en");
this.eventProvider.currentLang.subscribe(lang => {
this.translateService.use(lang);
});
event-provider.ts
import { EventEmitter } from '#angular/core';
export class EventProvider {
public currentLang: EventEmitter<string> = new EventEmitter();
setLang(val) {
this.currentLang.emit(val);
}
}
Import event-provider.ts to App Module and include in providers.
Now you can import it to any component where you need to change the language and emmit the value.
custom-header-component.ts
setLanguage(val:string) {
this.eventProvider.setLang(val);
}
Finally, i a solve this issue by using HttpClientModule in the import section of app.module.ts. maybe it helps.
First: Import HttpClientModule
Second: Use HttpClient instead of Http.
So, the code is as follow: app.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';
//translate related imports
import { TranslateModule, TranslateLoader } from '#ngx-translate/core';
import { TranslateHttpLoader } from '#ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '#angular/common/http';
#NgModule({
declarations: [
HomePage,
],
imports: [
IonicPageModule.forChild(HomePage),
HttpClientModule
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient ]
}
})
],
exports: [
HomePage
]
})
export class HomePageModule {}
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
In app.component.ts add this line in constructor.
import {TranslateService} from '#ngx-translate/core';
...
translate.setDefaultLang('en');//So English language set
And then you have to create two JSON files in ./assets/i18n/ path.
en.JSON
{
"title": "Translation demo",
"text": "This is a simple demonstration app for {{value}}"
}
Then use in your app with PIPE filter like this.
<h1>{{'title' | translate}}</h1>
OR
<h1 [translate]="'title'"></h1>
We can also pass a parameter.
<h1>{{'text' | translate:{'value':'ngx-translate'} }}</h1>
OR
<h1 [translate]="'text'" [translateParams]="{value: 'ngx-translate'}"></h1>

Angular 2 HTML page displaying twice instead of once

I have an Angular 2 app where the default page is a toolbar. It displays properly, but for some reason it is displaying twice, i.e. two identical toolbars on top of each other.
Here is my app.html code:
<p-toolbar>
<div class="ui-toolbar-group-left">
<button pButton type="button" label="Home" routerLink="/"></button>
</div>
<div class="ui-toolbar-group-right">
<button pButton type="button" label="About" routerLink="/about"></button>
<i class="fa fa-bars"></i>
<button pButton type="button" icon="fa-cog" routerLink="/test"></button>
</div>
</p-toolbar>
<router-outlet></router-outlet>
Here is my app.module.ts file:
import { AppComponent } from "./components/app.component";
import { AboutComponent } from "./components/about.component";
import { TunerComponent } from "./components/tuner.component";
import { CoreService } from "./services/core.service";
import { routing } from "./app.routes";
import { NgModule } from "#angular/core";
import { BrowserModule } from "#angular/platform-browser";
import { FormsModule } from "#angular/forms";
import { HttpModule } from "#angular/http";
import { SliderModule } from "primeng/primeng";
import { ButtonModule } from "primeng/primeng";
import { PanelModule } from "primeng/primeng";
import { ToolbarModule } from "primeng/primeng";
#NgModule({
imports: [
BrowserModule,
routing,
FormsModule,
HttpModule,
PanelModule,
ToolbarModule,
ButtonModule,
SliderModule
],
declarations: [
AppComponent,
AboutComponent,
TunerComponent
],
providers: [
CoreService
],
bootstrap: [
AppComponent
],
})
export class AppModule { }
Here is my app.routes.ts files:
import { ModuleWithProviders } from "#angular/core";
import { Routes, RouterModule } from "#angular/router";
import { AppComponent } from "./components/app.component";
import { AboutComponent } from "./components/about.component";
import { TunerComponent } from "./components/tuner.component";
const appRoutes: Routes = [
{
path: "about",
component: AboutComponent
},
{
path: "tuner",
component: TunerComponent
},
{
path: "",
component: AppComponent,
}
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
and here is my Index.cshtml file:
<cache vary-by="#Context.Request.Path">
<app>
Loading App Content...
</app>
</cache>
#section scripts {
<script src="~/vendor.bundle.js"></script> <!-- Vendor Bundle Includes all outside requirments -->
<script src="~/main.bundle.js"></script> <!-- Includes development code / Angular 2 -->
}
I've just updated from Angular RC4 to Angular 2.2.4. Everything seems in order, I'm unsure of why this is happening.