Populating a child router-outlet Angular2 not working - angular2-routing

The solution below was the first attempt as below.
Created app.module.ts and app.route.ts.
Created default for app.component.ts. The app.component router is working as expected so far for the first level routing.
Created a new module called Dashboard, with dashboard.module.ts and dashboard.routes.ts.
I imported the dashboard into the app.module.ts.
Created Sitebar,Header, and HeaderNav in the Dashboard.component.ts with child . But, no idea why the child navigation always shows in the first level router-outlet, instead of the child router-outlet.
Dashboard.component.ts code below.
<div class="wrapper">
<app-mydash-sidebar
[headerText]="'No Rush'"
[headerLink]="'http://www.bit-numbers.com'"
[headerLogoImg]="'/assets/img/angular2-logo-white.png'"
[backgroundColor]="'red'"
[backgroundImg]="'/assets/img/sidebar-5.jpg'"
[navItems]="navItems">
</app-mydash-sidebar>
<div class="main-panel">
<app-mydash-navbar [navItems]="navItems"></app-mydash-navbar>
<router-outlet ></router-outlet>
</div>
</div>
app.component.ts below.
<router-outlet></router-outlet>
Any idea?
app.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { SignupComponent } from './signup/signup.component';
import { EmailComponent } from './email/email.component';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
export const router: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'login-email', component: EmailComponent },
{ path: 'members', component: MembersComponent, canActivate: [AuthGuard] },
{ path: '', component: LoginComponent},
{ path: 'bookings', component: BookingsComponent },
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
mydash.routes.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AuthGuard } from '../auth.service';
import { MydashBookingsComponent } from '../mydash/mydash-bookings/mydash-bookings.component';
import { MydashChartComponent } from '../mydash/mydash-chart/mydash-chart.component';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export const Dashboardrouter: Routes = [
{
path: 'dashboard',
children: [{
path: '',
pathMatch: 'full',
component: MydashDashboardComponent
},
{
path: 'mybookings',
component: MydashBookingsComponent
}]
}
];
export const DashboardRouting: ModuleWithProviders = RouterModule.forChild(Dashboardrouter);
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AngularFireModule } from 'angularfire2';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { EmailComponent } from './email/email.component';
import { SignupComponent } from './signup/signup.component';
import { MembersComponent } from './members/members.component';
import { AuthGuard } from './auth.service';
import { routes } from './app.routes';
import { IconsComponent } from './icons/icons.component';
import { NotificationsComponent } from './notifications/notifications.component';
import { UserComponent } from './user/user.component';
import { MydashModule } from './mydash/mydash.module';
import { HomeComponent } from './home/home.component';
import { BookingsComponent } from './bookings/bookings.component';
import {FirebaseServiceService} from './services/firebase-service.service';
// Must export the config
export const firebaseConfig = {
...
};
#NgModule({
declarations: [
AppComponent,
LoginComponent,
EmailComponent,
SignupComponent,
MembersComponent,
IconsComponent,
NotificationsComponent,
UserComponent,
HomeComponent,
BookingsComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
MydashModule,
routes,
],
providers: [AuthGuard,FirebaseServiceService],
bootstrap: [AppComponent],
})
export class AppModule { }
mydash.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { MydashChartComponent } from './mydash-chart/mydash-chart.component';
import { MydashCheckboxComponent } from './mydash-checkbox/mydash-checkbox.component';
import { MydashCloseLayerComponent } from './mydash-close-layer/mydash-close-layer.component';
import { MydashFooterComponent } from './mydash-footer/mydash-footer.component';
import { MydashNavbarComponent } from './mydash-navbar/mydash-navbar.component';
import { MydashSidebarComponent } from './mydash-sidebar/mydash-sidebar.component';
import { MydashSidebarItemsComponent } from './mydash-sidebar-items/mydash-sidebar-items.component';
import { MydashTableComponent } from './mydash-table/mydash-table.component';
import { MydashTaskListComponent } from './mydash-task-list/mydash-task-list.component';
import { MydashUserProfileComponent } from './mydash-user-profile/mydash-user-profile.component';
import { MydashNavbarItemsComponent } from './mydash-navbar-items/mydash-navbar-items.component';
import { MydashBookingsComponent } from './mydash-bookings/mydash-bookings.component';
import { DashboardRouting} from './mydash.routes';
import { MydashDashboardComponent } from '../mydash-dashboard/mydash-dashboard.component';
export interface DropdownLink {
title: string;
routerLink?: string;
}
export enum NavItemType {
Sidebar = 1, // Only ever shown on sidebar
NavbarLeft = 2, // Left-aligned icon-only link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
NavbarRight = 3 // Right-aligned link on navbar in desktop mode, shown above sidebar items on collapsed sidebar in mobile mode
}
export interface NavItem {
type: NavItemType;
title: string;
routerLink?: string;
iconClass?: string;
numNotifications?: number;
dropdownItems?: (DropdownLink | 'separator')[];
}
#NgModule({
imports: [
CommonModule,
DashboardRouting,
],
declarations: [
MydashChartComponent,
MydashCheckboxComponent,
MydashCloseLayerComponent,
MydashFooterComponent,
MydashNavbarComponent,
MydashSidebarComponent,
MydashSidebarItemsComponent,
MydashTableComponent,
MydashTaskListComponent,
MydashUserProfileComponent,
MydashNavbarItemsComponent,
MydashBookingsComponent,
MydashDashboardComponent],
// These components are to export to allow access from the Dashboard. Do it manually, not done by ng CLI.
exports: [
MydashSidebarComponent,
MydashNavbarComponent,
MydashFooterComponent,
MydashChartComponent,
MydashTaskListComponent,
MydashTableComponent,
MydashUserProfileComponent,
MydashCloseLayerComponent,
MydashBookingsComponent
],
providers:[]
})
export class MydashModule { }

I solved the issue. The problem was because the dashboard component was missing in the file name mydash.routes.ts. I assigned the appropriate component underneath the path: 'dashboard', before the Child routes. Now, it works like a champ. Cheers!
The Answer code below.
path: 'dashboard',
component: MydashDashboardComponent,
children: [{

Related

Breadcrumbs in Angular don't show my children node details

I'm a beginner in Angular, and use BreadCrumb in my project. I have no problem with other pages, but when I want to show my child node details, I can only see the product id.
My project is here, and this is my code.
core.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { NavBarComponent } from './nav-bar/nav-bar.component';
import { RouterModule } from '#angular/router';
import { TestErrorComponent } from './test-error/test-error.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { ServerErrorComponent } from './server-error/server-error.component';
import { ToastrModule } from 'ngx-toastr';
import { BreadcrumbModule } from 'xng-breadcrumb';
import { SectionHeaderComponent } from './section-header/section-header.component';
#NgModule({
declarations: [NavBarComponent, TestErrorComponent, NotFoundComponent, ServerErrorComponent, SectionHeaderComponent],
imports: [
CommonModule,
RouterModule,
BreadcrumbModule,
ToastrModule.forRoot({
positionClass: 'toast-bottom-right',
preventDuplicates: true
})
],
exports: [NavBarComponent, SectionHeaderComponent]
})
export class CoreModule { }
shop.routing.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Routes, RouterModule } from '#angular/router';
import { ShopComponent } from './shop.component';
import { ProductDetailsComponent } from './product-details/product-details.component';
const routes: Routes = [
{ path: '', component: ShopComponent },
{ path: ':id', component: ProductDetailsComponent, data: { breadCrumb: { alias: 'productDetails' } }}
];
#NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class ShopRoutingModule { }
product-details.component.ts:
import { Component, OnInit } from '#angular/core';
import { IProduct } from '../../shared/models/product';
import { ShopService } from '../shop.service';
import { ActivatedRoute } from '#angular/router';
import { BreadcrumbService } from 'xng-breadcrumb';
#Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
product: IProduct;
constructor(private shopService: ShopService, private activatedRoute: ActivatedRoute, private bcService: BreadcrumbService) { }
ngOnInit(): void {
this.loadProduct();
}
loadProduct() {
this.shopService.getProduct(+this.activatedRoute.snapshot.paramMap.get('id')).subscribe(product => {
this.product = product;
this.bcService.set('#productDetails', product.name);
}, error => {
console.log(error);
});
}
}
I gave my project link to check all of my code if you need it. Thanks for the help!
This happened when I debugged my project on chrome:
seems you have a typing error,
in shop-routing-module.ts it should be breadcrumbnot breadCrumb
data: { breadcrumb: { alias: 'productDetails' } },

Routing through links in Angular2

I am new in Angular 2 and I am still in learning phase, but I stuck in a problem and not getting the solution to it. Please help.
I have made a view of a login, then a link to it after clicking the link it will redirect to home then clicking a link there it will redirect to some other view.
Below is my code structure:
app.routing.ts:
import { Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { UsersComponent } from './users/usercomponent';
export const routes: Routes = [
{ path: 'Home', component: HomeComponent },
{ path: 'Login', component: LoginComponent },
{ path: 'User', component: UsersComponent },
];
app.module.ts:
import { FormsModule } from '#angular/forms';
import { routes } from './app.routing';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { UsersComponent } from './users/usercomponent';
#NgModule({
imports: [BrowserModule, FormsModule, RouterModule.forRoot(routes)],
declarations: [AppComponent, LoginComponent, HomeComponent, UsersComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-initializer',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Some NAme'
}
app.component.html:
<a routerLink="Login">Login</a>
<br />
<div>
<router-outlet></router-outlet>
</div>
login.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'login',
template: `
<h1><a routerLink="Home">Home</a>
<a routerLink="User">Users</a></h1>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class LoginComponent {
constructor() {
}
}
The first page is working but after clicking home it is giving an error:
Cannot match any routes. URL Segment: 'Login/Home
I know that the link will be like / login, /home etc not like /login/home but how to implement it as I am not getting the solution for it and I am completely new to it.
Instead of giving only <h1><a routerLink="Home">Home</a>
you need to add / before the link like <h1><a routerLink="/Home">Home</a>.

ERROR in ./src/app/app.module.ts Module not found

I'm working on angular-cli. I got following errors.
ERROR in ./src/app/app.module.ts
Module not found: Error: Can't resolve '#angular/router/src/router_module' in
'E:\xampp\Angular-cli\Login\src\app'
# ./src/app/app.module.ts 13:0-69
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
I've this library #angular/router/src/router_module in my node_module. What is missing?
Here are required files.
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AdminAccount } from './admin/admin.component';
import { LoginForm } from './login/login.component';
import { FileData } from './filedata/filedata.component';
import { ROUTER_PROVIDERS } from "#angular/router/src/router_module";
import { RouterModule, Routes, ROUTES } from "#angular/router";
import { Http, Response } from "#angular/http";
import { Route } from './router/router.component';
#NgModule(
{
imports: [RouterModule ,Route, BrowserModule, Http, Response, AdminAccount, LoginForm, FileData, Route],
declarations: [AppComponent],
providers: [ROUTER_PROVIDERS],
bootstrap: [AppComponent]
})
export class AppModule { }
router.component.ts
import { Component, OnInit } from '#angular/core';
import { RouterModule } from "#angular/router";
import { LoginForm } from "../login/login.component";
import { AdminAccount } from "../admin/admin.component";
export const Route = RouterModule.forRoot(
[
{ path: '/', component: LoginForm },
{ path: '/admin', component: AdminAccount }
]);
app.component.ts
import { Component } from "#angular/core";
import { LoginForm } from "./login/login.component";
import { AdminAccount } from "./admin/admin.component";
import { Routes, RouterModule } from "#angular/router";
import { FileData } from "./filedata/filedata.component";
#Component(
{
selector: "root",
templateUrl: "./app.component.html",
})
export class AppComponent {}
If need more file let me know.
#Fahad Nasir Here's AdminAcount.
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
#Component(
{
selector: "admin",
templateUrl: "./admin.component.html",
})
export class AdminAccount
{
adminUser = document.cookie.split("??")[0];
adminPass = document.cookie.split("??")[1];
constructor(public router: Router)
{
if (document.cookie !== undefined)
{
if (this.adminUser == "admin" && this.adminPass == "admin")
{
console.log("Welcome!");
}
else
{
this.router.navigate(["Loginform"]);
console.log("Redirect!");
}
}
else
{
console.log("Error: Undefined Login!");
}
}
}
Here Have a look

Adding Dragular to Angular2 Application: document is not defined

I am fairly new to Angular2 and I am having issues adding Dragula to my application. When I run the application an error is thrown prior to loading the home page:
Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: document is not defined
The error message mentions Prerending which I suspect is in relation to the project using asp-prerender-module.
I've tried to follow official tutorials from Dragula and forum posts. Below are my app.module and component file snippets (... denotes summarised code):
app.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
...
import { SearchComponent } from './components/search/search.component';
import { BrowserModule } from '#angular/platform-browser';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { Injectable } from '#angular/core';
import { DragulaModule } from 'ng2-dragula';
#NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
...
SearchComponent
],
imports: [
UniversalModule,
BrowserModule,
FormsModule,
DragulaModule,
CommonModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
...
{ path: 'search', component: SearchComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModule {
}
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService, DragulaService]
})
I suspect I am missing an a step when including Dragula, but I cannot figure out where. I have included both dragula (^3.7.2) and ng2-dragula (^1.3.0) in my package.json file.
your DragulaService initialization is wrong!! check Dragula documentation link
search.component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { SearchService } from '../../services/search.service';
import { DragulaService } from 'ng2-dragula';
#Component({
selector: 'search',
template: require('./search.component.html'),
providers: [SearchService]
})
expoert searchcomponent{
constructor(private dragulaService: DragulaService) {
console.log('DragulaService created');
}
}
Now you can play with drag and drop
If you want more control over drag and drop you can add events and options to dragulaService.
constructor(private dragulaService: DragulaService) {
dragulaService.drag.subscribe((value) => {
console.log(`drag: ${value[0]}`);
this.onDrag(value.slice(1));
});
dragulaService.drop.subscribe((value) => {
console.log(`drop: ${value[0]}`);
this.onDrop(value.slice(1));
});
dragulaService.over.subscribe((value) => {
console.log(`over: ${value[0]}`);
this.onOver(value.slice(1));
});
dragulaService.out.subscribe((value) => {
console.log(`out: ${value[0]}`);
this.onOut(value.slice(1));
});
}
private onDrag(args) {
let [e, el] = args;
// do something
}
private onDrop(args) {
let [e, el] = args;
// do something
}
private onOver(args) {
let [e, el, container] = args;
// do something
}
private onOut(args) {
let [e, el, container] = args;
// do something
}

Error while configuring routes in Angular 2

i have been working with a product list Project and while configuring routes to navigate between different views, I get a red squiggly under the '#Routes' decorator and when i hover over the Routes, it says 'Routes only refers to a type, but is being used as a value here'. I researched in so many sights including here and tried many different ways to resolve this but I could not find out the issue.
app.component.ts
import { Component } from '#angular/core';
import { ProductListComponent } from './products/product-list.Component';
import { ProductService } from './products/product.service'
import { Routes } from '#angular/router';
import 'rxjs/Rx'; // Load all features
import { WelcomeComponent } from './home/welcome.component'
#Component({
selector: 'pm-app',
template: `
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{pageTitle}}</a>
<ul class='nav navbar-nav'>
<li><a>Home</a></li>
<li><a>Product List</a></li>
</ul>
</div>
</nav>
</div>
` ,
entryComponents : [ProductListComponent],
providers: [ProductService]
})
#Routes([
{ path: '/welcome' , name: 'Welcome' , component: WelcomeComponent, useAsDefault: true},
{ path: '/products' , name: 'Products' , component: ProductListComponent }
])
export class AppComponent {
pageTitle:string = 'Acme Product Management';
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ProductListComponent } from './products/product-list.Component';
import { HttpModule } from "#angular/http";
import { RouterModule } from '#angular/router'
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule,FormsModule,HttpModule,RouterModule],
declarations: [ AppComponent,ProductListComponent,ProductFilterPipe,StarComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
welcome.compnent.ts
import { Component } from '#angular/core';
#Component({
templateUrl: 'app/home/welcome.component.html'
})
export class WelcomeComponent {
public pageTitle: string = 'Welcome';
}
I think my coding is fine. But unable to get the expected result. Please Help!
Found out, the issue is... with RC5, Routes is an array of path's & is no more a Decorator, and you have to import 'RouterModule' instead of 'provideRouter'. While exporting you have to use 'RouterModule.forRoot'.
Also with RC5, we no longer specify the string name of the component while configuring routes instead we only specify the path & component only. And we no longer use the prefix '/' for the path. Also we no longer using useAsDefault instead we use redirectTo property to configure the default path.
I have used a separate module to do my route configurations instead of doing it in the root component as earlier. An updated version of my route configuration is given as below. Hope this will be helpful.
app.routes.ts
import { Routes, RouterModule } from '#angular/router';
import { ProductListComponent } from './products/product-list.Component';
import { WelcomeComponent } from './home/welcome.component'
import { ProductDetailComponent } from './products/product- detail.component';
const routes: Routes = [
{
path: 'welcome' ,
component: WelcomeComponent,
},
{
path: 'products' ,
component: ProductListComponent
},
{
path: 'product/:id' ,
component: ProductDetailComponent
},
{
path:'',
redirectTo:'/welcome',
pathMatch:'full'
},
];
export const routing = RouterModule.forRoot(routes);

Resources