Yesterday I asked a question about an another specific thing of angular 2 routing and the answer was satisfying for me Angular 2 — navigate through web pages without reloading a component that is common for those pages . But when I got back to examining these things, I encountered a problem again. Here's the new version of the app: http://ivan-khludov.com/ . What if I want the pages of the private section to have a shared component (a counter in my example), don't reload it each time I navigate withing the section and at the same time display different components at different pages - the dashboard component at private/dashboard and the inbox component at private/inbox? Is it possible to do without reloading the counter and without storing the last value of the counter in memory? This is the entry point of the application and the root module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { ROUTES } from './routes';
import { AppWrapper } from './components/app-wrapper';
import { PublicSection } from './components/public';
import { PrivateSection } from './components/private';
import { Counter } from './components/counter';
import { Dashboard } from './components/private/dashboard';
import { Inbox } from './components/private/inbox';
#NgModule({
imports: [
BrowserModule,
CommonModule,
HttpModule,
RouterModule.forRoot(ROUTES)
],
declarations: [
AppWrapper,
PublicSection,
PrivateSection,
Counter,
Dashboard,
Inbox
],
providers: [
],
bootstrap: [
AppWrapper
]
})
class RootModule {}
platformBrowserDynamic().bootstrapModule(RootModule);
Routing:
import { Routes } from '#angular/router';
import { AppWrapper } from '../components/app-wrapper';
import { PublicSection } from '../components/public';
import { PrivateSection } from '../components/private';
export const ROUTES: Routes = [
{
path: '',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'section-1',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'public/:page',
component: PublicSection
},
{
path: 'private',
redirectTo: '/private/dashboard',
pathMatch: 'full'
},
{
path: 'private/:page',
component: PrivateSection
}
];
The private section component:
import { Component } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'private',
template: `
<h2>Private section — {{page}}</h2>
<counter></counter>
<dashboard></dashboard>
<inbox></inbox>
`
})
export class PrivateSection {
private page: string;
private sub: any;
constructor(
private route: ActivatedRoute
) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.page = params['page'];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
The dashboard component:
import { Component } from '#angular/core';
#Component({
selector: 'dashboard',
template: `
<div>dashboard text: lorem ipsum</div>
`
})
export class Dashboard {
}
The inbox component:
import { Component } from '#angular/core';
#Component({
selector: 'inbox',
template: `
<div>inbox text: dolor sit amet</div>
`
})
export class Inbox {
}
Thanks in advance for your answers.
Related
I am trying to learn Angular 2 and play with it now. But I don't know why it doesn't go to start page from AppComponent. As long as I know, this has to move to test page and show "test" text. But when I run this, it only displays "Hello" which is app.component text. If I enter /test url, there is 404 error. Is this because the test component is not loaded successfully?
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { test } from './test';
#NgModule({
imports: [
BrowserModule,
routing
],
declarations: [
AppComponent,
test
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.routing.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { test } from './test.index';
const routes: Routes = [
{ path: '', component: test },
{ path: 'test', component: test },
{ path: '**', redirectTo: '' },
];
export const routing = RouterModule.forRoot(routes);
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<h1>Hello </h1>`,
})
export class AppComponent { }
test.ts
import { Component } from '#angular/core';
#Component({
selector: 'test-app',
template: `<h1>test </h1>`,
})
export class test {}
Include '<router-outlet></router-outlet>' in your appcomponent template:
<div>
<h3>App component</h3>
</div>
<div>
<router-outlet></router-outlet>
</div>
It looks like you need to provide a <router-outlet></router-outlet> in your app.component.ts template.
So the test component isn't being loaded because it can't inject the component into anything without the <router-outlet>.
https://angular.io/tutorial/toh-pt5#add-routeroutlet
I'm having an issue with my Angular2/Meteor application.
I'm trying to redirect to a component from an other but it doesn't seem to load the first time. However, when I refresh the page, it loads perfectly.
When I debug, I see my html view without any of the variables displaying, my variables have values that seems correct, but they doesn't show on the View.
This is my Guard:
import { CanActivate } from "#angular/router";
import { Meteor } from 'meteor/meteor';
import { Router } from '#angular/router';
import { Injectable } from '#angular/core';
#Injectable()
export class RouteGuardService implements CanActivate {
constructor(public router: Router) { }
canActivate() {
if (Meteor.userId() != undefined) {
return true;
}
else {
let link = ['accueil'];
this.router.navigate(link);
return false;
}
}
}
My route.module :
import { Route } from '#angular/router';
import {AccueilComponent} from "./pages/accueil/accueil.component";
import {ChannelsComponent} from "./pages/channel/channels.component";
import { RouteGuardService } from './services/routeGuard.service';
export const routes: Route[] = [
{ path: '', component: AccueilComponent },
{ path: 'accueil', component: AccueilComponent, pathMatch: 'full' },
{ path: 'channel', component: ChannelsComponent, canActivate: [RouteGuardService], pathMatch: 'full'},
];
I hope I was clear with my explanation. Do not hesitate to ask more information.
Thanks !
EDIT:
My app.module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import { AccountsModule } from 'angular2-meteor-accounts-ui';
import { AppComponent } from './app.component';
import { MomentModule } from "angular2-moment";
import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap';
import { ChannelModal } from './pages/channel/channel_search/channel-list.modal';
import { RouteGuardService } from './services/routeGuard.service';
import { AccueilComponent } from "./pages/accueil/accueil.component";
import { LOGIN_DECLARATIONS } from './pages/login';
import { CHANNEL_DECLARATIONS } from './pages/channel';
import { routes } from './app.routes';
#NgModule({
imports: [
RouterModule.forRoot(routes),
Ng2DragDropModule.forRoot(),
ModalModule.forRoot(),
BrowserModule,
AccountsModule,
FormsModule,
ReactiveFormsModule,
MomentModule,
BootstrapModalModule,
],
declarations: [
AppComponent,
AccueilComponent,
...LOGIN_DECLARATIONS,
...CHANNEL_DECLARATIONS,
ChannelModal
],
bootstrap: [
AppComponent
],
entryComponents: [
ChannelModal
],
providers:[
RouteGuardService
]
})
export class AppModule { }
Alright I found an answer. I don't know if it's the best solution, but at least it's working.
this.zone.run(() => this.router.navigate(['channel']));
This solve my problem.
I found a project ng2-admin from https://github.com/akveo/ng2-admin , and this is online demo http://akveo.com/ng2-admin/
I am confused about PagesModule bootstrap process. Default AppModule bootstrap, how did it contine show /#/pages/dashboard content?
In app.module.ts:
import { NgModule, ApplicationRef } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { TranslateService } from '#ngx-translate/core';
/*
* Platform and Environment providers/directives/pipes
*/
import { routing } from './app.routing';
// App is our top level component
import { App } from './app.component';
import { AppState, InternalStateType } from './app.service';
import { GlobalState } from './global.state';
import { NgaModule } from './theme/nga.module';
import { PagesModule } from './pages/pages.module';
// Application wide providers
const APP_PROVIDERS = [
AppState,
GlobalState
];
export type StoreType = {
state: InternalStateType,
restoreInputValues: () => void,
disposeOldHosts: () => void
};
/**
* `AppModule` is the main entry point into Angular2's bootstraping process
*/
#NgModule({
bootstrap: [App],
declarations: [
App
],
imports: [ // import Angular's modules
BrowserModule,
HttpModule,
RouterModule,
FormsModule,
ReactiveFormsModule,
NgaModule.forRoot(),
NgbModule.forRoot(),
PagesModule,
routing
],
providers: [ // expose our Services and Providers into Angular's dependency injection
APP_PROVIDERS
]
})
export class AppModule {
constructor(public appState: AppState) {
}
}
I know this file is app entrance.
in app.routing.ts file:
import { Routes, RouterModule } from '#angular/router';
import { ModuleWithProviders } from '#angular/core';
export const routes: Routes = [
{ path: '', redirectTo: 'pages', pathMatch: 'full' },
{ path: '**', redirectTo: 'pages/dashboard' }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: true });
It only tell browser redirec to "#pages/dashboard", but there is no related component here.
In app.component.ts, the template is:
template: `
<main [class.menu-collapsed]="isMenuCollapsed" baThemeRun>
<div class="additional-bg"></div>
<router-outlet></router-outlet>
</main>
`
There is no other custom tags except router-outlet.
I am confused how to make main AppModule work with PagesModule in application.
Thanks very much.
I have a component in angular 2 as shown below
login.component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
})
export class HomeComponent {
}
The appModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'Account/Login', component: LoginComponent }
];
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule, RouterModule.forRoot(appRoutes)],
declarations: [LoginComponent, HomeComponent],
bootstrap: [HomeComponent]
})
export class AppModule { }
login.cshtml
#{
ViewData["Title"] = "Login";
}
<login-app>looding...</login-app>
partialLogin.cshtml
<router-outlet></router-outlet>
<p>THis is test</p>
Routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "spa-fallback",
template: "{*url}",defaults: new { controller = "Home", action = "Index" });
});
I have use the angular 2 routing as you can see in the appmodule.ts.If I navigate to homepage i,e Home/Index I will get an error as The selector "login-app" did not match any elements and when I navigate to Account/Login I will get an error as The selector "Home-app" did not match any elements.I know the the condition on appmodule is not working. How can I make this work. Please anyone can solve this issue
you are getting this error because you didn't import all your other component in you ngModule file. add them in declaration just like you have imported LoginComponent
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule],
declarations: [LoginComponent],<-- add all your component here
bootstrap: [LoginComponent]
})
export class AppModule { }
Below is an example of how to add route in Angular2:
//Create new app.module.ts file
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './Components/login.Component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
//Import the above define route in your App module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
//Import your route file
import { routing } from './app.routing';
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule,routing,],
declarations: [LoginComponent],
bootstrap: [LoginComponent]
})
export class AppModule { }
Finally the working code.Call the respective selector in HTML page
AppModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent,LoginComponent, HomeComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.Component.ts
import { Component } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
#Component({
selector: 'main-app',
template: '<router-outlet></router-outlet>'
})
export class AppComponent { }
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
`
})
export class HomeComponent {
}
login.Component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}
I have a one main page and I want to separate header body and footer. Because in other page I wont be needed header.
_layout.cshtml
<!DOCTYPE html>
<html>
<head>
<base href="/" />
</head>
<body>
<main-app></main-app>
</body>
</html>
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { EqualValidator } from "./Validation/equal.validator.directive";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
import { DashBoardComponent } from "./Components/dashBoard.Component";
import { FooterComponent } from "./Components/footer.Component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent,children:[
{path: '',component: FooterComponent,outlet: 'footer'}]},
{ path: 'DashBoard/Index', component: DashBoardComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent, LoginComponent, HomeComponent, DashBoardComponent, EqualValidator,FooterComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
If I remove the child routing the application works good. I have added the forChild() root also but the footer component is not been loaded.
Here I found the working sample
https://plnkr.co/edit/sgGDpti43GPM5cHntPpu?p=preview
But I am facing the Cannot match any routes: '' error
home.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<br>
<br>
<br>
my home!!!!
<br>
<br>
<br>
<router-outlet name="footer"></router-outlet>
`
})
export class HomeComponent {
}
footer.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Footer-app',
templateUrl: '<p>Copy rights emakitri 2017</p>'
})
export class FooterComponent {
constructor() {
console.log("test");
}
}