Angular routerlink navigate to simple page instead of page/page - javascript

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".

Related

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 router not loading the proper component

I am beginner with angular and I have the followings routes.
app.routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { FrameComponent } from './ui/frame/frame.component';
import { NotFoundComponent } from './common/not-found/not-found.component';
const routes = [
{
path: 'login',
loadChildren: 'src/app/login/login.module#LoginModule'
},
{
path: 'dashboard',
component: FrameComponent,
loadChildren: 'src/app/dashboard/dashboard.module#DashboardModule'
},
{
path: "**",
component: NotFoundComponent,
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
dashboard.routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { OverviewComponent } from '../overview/overview.component';
const routes = [
{
path: '',
children:[
{
path: 'overview',
component: OverviewComponent,
//outlet: 'dashboard-inside'
}
]
},
];
#NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class DashboardRoutingModule { }
When navigating to /dashboard it loads the FrameComponent from the AppRoutingModule.
But when navigating to /dashboard/overview it loads NotFoundComponent instead of OverviewComponent from second router.
I am still a beginner with Angular. What am I doing wrong?
I think you didn't define your routes correctly
{
path: 'dashboard',
component: FrameComponent,
loadChildren: 'src/app/dashboard/dashboard.module#DashboardModule'
}
This piece of code doesn't load lazily - you are not loading the childern over here you are just loading the component FrameComponent so angular does it for you
If your FrameComponent is part of AppModule you can just remove the loadChildren from the path and the angular will do the same routing for you
If it is not the part of AppModule then try something like this
app-routing.module.ts
{
path: 'dashboard',
loadChildren: 'src/app/dashboard/dashboard.module#DashboardModule'
}
Just load another module from the path and load the component you want from that module
dashboard-routing.module.ts
{
path: '',
component: FrameComponent,
children:[
{
path: 'overview',
component: OverviewComponent,
//outlet: 'dashboard-inside'
}
]
}
Make sure you have declared the FrameComponemt inside the DashboardModule and that will make you to load the route you want
Now if the path is /dashboard angular will load the dashboard module and check for the path '' next to the /dashboard so it will load the FrameComponent then when you try to access path /dashboard/overview routing will load the child route and OverviewComponet will be loaded
Hope everything will work good - please feel free to reach me if you have any doubts - Happy coding :)
You can remove component: FrameComponent from the dashboard route and move it into the dashboard routing module.
{
path: 'dashboard',
loadChildren: 'src/app/dashboard/dashboard.module#DashboardModule'
},
{
path: '',
component: FrameComponent,
children:[
{
path: 'overview',
component: OverviewComponent,
}
]
},
And I guess you should import your modules in core one.
Your definition in dashboard.routing.module.ts is wrong.
Try this instead:
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { OverviewComponent } from '../overview/overview.component';
const routes = [
{
path: 'overview', // <-- should be in root.
component: OverviewComponent,
},
];
#NgModule({
imports: [
RouterModule.forChild(routes)
],
exports: [RouterModule]
})
export class DashboardRoutingModule { }

Using same URL for multiple diferent ROUTES - Angular 2+

I need to make a angular application to work with same url for multiple routes. Example:
Route 1. Instead of navigating to:
/partner/urlparameter
Navigate to:
/partnerurlparameter
Route 2. Instead of navigating to:
/user/urlparameter
Navigate to:
/userurlparameter
Where the path is "/" followed by a dynamic value which is the parameter.
Is there a way do achieve that?
Here is how my route is configured:
{ path: '/partner/:partnerId', component: PartnerComponent },
{ path: '/customer/:customerId', component: CustomerComponent },
I want to have something like this:
{ path: '/partner/:partnerId', component: PartnerComponent },
{ path: '/:customerId', component: CustomerComponent },
Here is an example of what you want to achieve, follow the link for same.
Let me know if there are any changes.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { CustomerComponent } from '../customer/customer.component';
import {PartnerComponent} from '../partner/partner.component';
export const routes: Routes = [
{ path: 'partner/:partnerId', component: PartnerComponent },
{ path: ':customerId', component: CustomerComponent },
{ path: '', component: HelloComponent, pathMatch:'full' },
];
#NgModule({
imports: [BrowserModule, FormsModule, RouterModule.forRoot(routes)],
declarations: [AppComponent, HelloComponent, CustomerComponent, PartnerComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

In Angular2 routing, the URL changed but the content doesn't update

I am a beginner of Angular2. When I am learning angular2 routing service from https://angular.io/tutorial/toh-pt5. I want to have herocomponent always displayed so I in the app.component.html like this:
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
<a routerLink="/dummy">Dummy</a>
</nav>
<app-heroes></app-heroes>
<router-outlet></router-outlet>
<app-messages></app-messages>
And here is the app-routing.module.ts:
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import {DummyComponentComponent} from './dummy-component/dummy-component.component';
const routes: Routes = [
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent },
{path: 'dummy',component:DummyComponentComponent}
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Strangely, when I click a hero on /dashboard or /heroes page it can direct to the correct URL and show the correct hero detail.
However, when I am on /detail/{{hero.id}} and click the hero on the hero component it can redirect the URL but the content in doesn't update. Can someone please help me with this?
if below is not issue then it should be issue that you are just changing parameter url that is reason its not updating
//put this code in your hero.component.ts file
ngOnInit() {
this.route.params.subscribe((params) => {
this.id = +params['id'];
this.loadComponentAgain();
});
}
above code monitor change in param value and update your component according to it.
There is issue because of this html
<app-heroes></app-heroes>
<router-outlet></router-outlet>
you are loading app-heroes component out side router-outlet, it should be loaded under router-outlet, so you should do this
<!-- <app-heroes></app-heroes> remove this-->
<router-outlet></router-outlet>
For changing a route with dynamic value you need to set your routerLink like this
[routerLink]="['/detail',hero.id]"

How to load new route in main route

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.

Categories

Resources