How to load new route in main route - javascript

Currently I'm new to Angular. I was learning routing topic but seems to stuck at a point where I want to load new route in main route. My app.module looks like
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import {HttpModule} from '#angular/http';
import {RouterModule, Routes} from '#angular/router';
// COMPONENTS
import {AppProduct} from './product.compnent';
import {AppFamily} from './family.component';
const appRoutes: Routes = [
{path: 'Family', component: AppFamily},
{path: 'Product', component: AppProduct}
]
#NgModule({
imports: [ BrowserModule, HttpModule, RouterModule.forRoot(appRoutes)],
declarations: [ AppComponent, AppFamily, AppProduct],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component
import { Component } from '#angular/core';
import {IProducts} from './IProduct';
import {ProductService} from './products.service'
// FAMILY IMPORTS
import {IFamily} from './IFamily'
import {familyService} from './family.service'
#Component({
selector: 'hello-world-app',
templateUrl: "app/app.component.html",
providers: [ProductService, familyService]
})
export class AppComponent {
iproducts: IProducts[];
familyMembers: IFamily[];
constructor(
private _product: ProductService,
private _family: familyService){
}
ngOnInit():void{
this._family.getAllFamilyMembers()
.subscribe(_successLog => {
this.familyMembers = _successLog;
})
}
}
app.component.html
<ul>
<li>
<a [routerLink]="['/Product']">
Product
</a>
</li>
<li>
<a [routerLink]="['/Family']">
Family
</a>
</li>
</ul>
<router-outlet>
</router-outlet>
Now when I serve my server all goes good except for my /Product and /Family route is loaded in <router-outlet></router-outlet> but I don't want navigation menu to appear when I visit /Product in other words I want that my route should load in parent route no child routing.
Any help would be appreciated !

You should define your children module in your appRoutes constant as this:
{ path: '/childPath',
component: ChildComponent,
children: [
{path: 'about',
loadChildren: './path/to/children.module#ModuleName'}
]
}

The answer by Mr. Deer is correct for lazy loading - however, you don't always want to do that. If you want to just have child components, you should do:
{ path: '/childPath',
component: ChildComponent,
children: [
{path: 'about',
component: SecondChildComponent
]
}
That said, lazy loading is generally preferred.

Related

Angular Routing not working with different components

I have two components. Component A and Component B. I want to create a navigation system in component A that on click will load the appropriate element in component B.
I know within the same component we can use routerLink and router-outlet. But how can i achieve the same in my case ??
for example:
Component A
<a routerLink="/userHome"></a>
Component B
<router-outlet></router-outlet>
And my routing module is :
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import {RouterModule, Routes} from '#angular/router';
import {UserHomeMainBodyComponent} from './components/user-home-
main-body/user-home-main-body.component';
import {UserNotificationsBodyComponent} from './components/user-
notifications-body/user-notifications-body.component';
const routes: Routes = [
{ path: 'userHome', component: UserHomeMainBodyComponent},
{path: 'userNotifications', component:UserNotificationsBodyComponent}
];
#NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }

Angular routerlink navigate to simple page instead of page/page

I have two pages, home and player, and i want on the home page to nabvigate to the player page but without being with this format home/player
When i use routerLink="player", it got an error because the link goes to home/player, instead of just player. How can i make that happen?
app-routing module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import {AddPlayerComponent} from './pages/add-player/add-player.component';
import {RouterModule, Routes} from '#angular/router';
import {HomeComponent} from './pages/home/home.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'Player', component: AddPlayerComponent }
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
Try routerLink = "/Player. Notice how in your defined routing module the "Player" is capitalized, as well as the missing "/" in routerLink. See https://angular.io/api/router/RouterLink for more clarification
Try Adding <base href="/"> code in head of index.html page and correct the code to routerLink="/Player".

Not able to display component via routing in Angular

I have 3 components: A, B, and C. I want to display a button named "Component B" inside component A. On clicking the button, it should display B component with a link saying "Component C". On clicking the link it should display c component which says "C component works"
The app module is:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';
#NgModule({
declarations: [
AppComponent,
AComponent,
BComponent,
CComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The app routing module is:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';
import { AppComponent } from './app.component';
const routes: Routes = [
{
path: 'a',
component: AComponent,
},
{
path: 'a',
component: BComponent,
},
{
path: 'c', component: CComponent
},
{
path: '**', component: AppComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
The app.component.html is :
<h3>Routing and Navigation</h3>
<router-outlet></router-outlet>
The A component is:
<h4>It is Component A</h4>
<a class="button" routerLink="a" routerLinkActive='active'>B component</a>
<router-outlet></router-outlet>
The B component is:
<a routerLink="b">C component</a>
<router-outlet></router-outlet>
The C component is:
<p>C component works</p>
Kindly help me with this as I am learning to route in Angular. I will be glad if I know the area of improvement in the code and a proper guidance. Thank you.
here is a stackBlitz with a working example that has all 3 components.
https://angular-7ucy2h.stackblitz.io/a
the thing about angular routing is that if you want a child route to show inside of a parent route you will have to add that route as a child.
in your case C is a child of B and B is a child of A.
const routes: Routes = [
{
path: 'a',
component: AComponent,
children: [
{path: 'b', component: BComponent, children: [
{path: 'c', component: CComponent}
]},
]
},
];
You don't need routing at all to do what you are asking. If Component B & C are "inside" component A, then you don't route to them. you just display them.
<h4>It is Component A</h4>
<a class="button" (click)="showBFlg = true">B component</a>
<div *ngIf="showBFlg">
<app-b></app-b>
<a class="button" (click)="showCFlg = true">C component</a>
</div>
<app-c *ngIf="showCFlg"></app-c>

How do I use a component from a different module to be the main component in routing declarations

Angular newbie here, your patience is highly appreciated.
What am I trying to achieve?
I'm trying to use the component in my auth module(i.e login
component) as the base component for the route myapp.com/login
Assuming that when embedding in **app.component.html works fine, the same should be true when I put that in app-routing.module.ts
code for app-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: '/login', component: LoginComponent}, //Cannot find name 'LoginComponent'.ts(2304)
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
My component structure
I have an auth module which has a login and register components
And the basic ng-cli generated app structure.
code for authmodule
auth.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
#NgModule({
declarations: [RegisterComponent, LoginComponent],
exports:[RegisterComponent,LoginComponent],
imports: [
CommonModule
]
})
export class AuthModule { }
code for app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {AppCommonsModule} from './app-commons/app-commons.module';
import {AuthModule} from './auth/auth.module'
import { HomeComponent } from './home/home.component'
#NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AppCommonsModule,
AuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You are referring to LoginComponent in routing file but not importing it.
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: '/login', component: LoginComponent}, //Cannot find name 'LoginComponent'.ts(2304)
];
Add import statement and I believe it should fix typescript error.
import { LoginComponent } from './login/login.component';
You can't directly refer components declared as part of other modules in AppRoutingModule. You have to delegate the routing of LoginComponent to AuthModule by creating an AuthRoutingModule. Then in AppRoutingModule, create a route for login and pass the control to AuthRoutingModule.
Follow the below steps to create a route for LoginComponent.
Create a new file called AuthRoutingModule and include routes for the components in AuthModule in this file.
auth-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from './login.component';
const authRoutes: Routes = [
{
path: '', // considering LoginComponent as the root path for AuthModule. This will be referred as 'login' from AppRoutingModule
pathMatch: 'full', // this is important to correctly match the empty path
component: LoginComponent
}
];
#NgModule({
imports: [RouterModule.forChild(authRoutes)],
exports: [RouterModule]
})
export class AuthRoutingModule {}
Note that forChild() method used here. RouterModule.forRoot() should be used only once and it should preferrable be there in AppRoutingModule. RouterModule.forChild() is used for creating routes for other child modules (and hence the forChild name).
Import AuthRoutingModule in AuthModule file.
Modify your AppRoutingModule file as below.
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { HomeComponent } from './home.component';
const authRoutes: Routes = [
{
path: '',
pathMatch: 'full', // this is important to correctly match the empty path
component: HomeComponent
},
{
path: 'login',
loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
// now this will refer the root path of AuthRoutingModule
},
// Redirect all invalid URLs to HomeComponent
{
path: '**',
redirectTo: '/'
}
];
#NgModule({
imports: [RouterModule.forRoot(authRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
As shown in the above code snippet, if you want to load a component from a child module for a particular route, AppRoutingModule should redirect the control to the child module using the loadChildren property.
You would have already imported both AppRoutingModule and AuthModule in your AppModule file. Just make sure that you are loading the AppRoutingModule first and then other child modules with routing (i.e., AuthModule in your case).
If you want lazy loading, remove all child modules(with routes) from AppModule imports. More on lazy loading here.
Refer Angular official docs for more information on child modules routing.
I have also created a sample stackblitz app for demo purposes.

Angular nested route with param "Cannot match any routes"

Here are the 3 routes I'm working on:
game/:id
game/:id/pricing
game/:id/history
I'd like the game/:id to be the parent view, and house a <router-outlet> for the children to render inside of it. However, I keep getting this error: Cannot match any routes. URL Segment: 'game/1/history'.
Any help is appreciated.
Router Module:
import { NgModule } from "#angular/core";
import { RouterModule, Routes } from "#angular/router";
import { CommonModule } from "#angular/common";
import { GameComponent } from "./game.component";
import { GamePricingComponent } from './game-pricing.component';
import { GameHistoryComponent } from './game-history.component';
const routes: Routes = [
{ path: 'game/:id', component: GameComponent, children: [
{ path: 'pricing', component: GamePricingComponent, outlet: 'game' },
{ path: 'history', component: GameHistoryComponent, outlet: 'game' }
]},
];
#NgModule({
imports: [
RouterModule.forRoot(routes),
CommonModule
],
declarations: [
GameComponent,
GamePricingComponent,
GameHistoryComponent
],
exports: [
RouterModule
]
})
export class RoutingModule {}
GameComponent:
The game/:id route is the parent view, which has a <router-outlet name="game"> inside of it for the children (pricing & history) to render into.
import { Component } from "#angular/core";
#Component({
template: `
<div>Game stuff</div>
<router-outlet name="game"></router-outlet>
`
})
export class GameComponent {}
RootModule
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { RoutingModule } from "./routing.module";
#NgModule({
imports: [
BrowserModule,
RoutingModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export default class AppModule { }
AppComponent
import { Component } from '#angular/core';
#Component({
selector: 'app',
template: `
<div class="base">
<router-outlet></router-outlet>
</div>
`,
})
export class AppComponent {}
After a (long) while, I was able to solve this by removing the naming for the <router-outlet>. Turns out, single child router outlets 'just work' - so naming isn't required...
However, as of writing this, I'm still unaware of how to use router outlet naming within child routes. If anyone wants to elaborate here, I'd be more than appreciative. (maybe naming only works if there's more than 1 outlet at the same level?)

Categories

Resources