Angular 2 Routes

梦想的初衷 提交于 2019-12-14 03:36:14

问题


I have one router-outlet in my app.html .problem is i have 3 (post,admin,addposts)component except app.component .in my posts component i have dropdown menu onece i click dropdown i want load addposts and the url should be look like this post/addposts. any idea how to do this

this is my app.routes.ts

   const routes: Routes = [

      { path: '',  redirectTo: 'main', pathMatch: 'full'},
      { path: 'main', component:AdminBodyComponent  },
      { path: 'admin', component:AdminComponent  },
      { path: 'posts',component:PostsComponent},
      { path: 'addposts',component:AddPostComponent}];

回答1:


first install router via: npm install router

import { Routes, RouterModule } from '@angular/router';


export const router: Routes = [
   { path: '',  redirectTo: 'main', pathMatch: 'full'},
  { path: 'main', component:AdminBodyComponent  },
  { path: 'admin', component:AdminComponent  },
  { path: 'posts',component:PostsComponent},
  { path: 'addposts',component:AddPostComponent}];

export const routes: ModuleWithProviders = RouterModule.forRoot(router);
step2:
inject into your .ts file
constructor(
  private router:Router,
  ...
)
step3:
this.router.navigate(['/addposts']);

step4:
<base href="/">

if you want to use specific router go for this step4:




回答2:


Oprion 1:

If you can add an anchor tag that will be simplest.

<a routerLink="/addposts" routerLinkActive="active">Add Post</a>

Option 2:

Follow these 3 simple steps.

Step 1: Import the angular router

import { Router } from '@angular/router';

Step 2: Inject the value using dependency injection

constructor(
      private router:Router,
      ...
)

Step 3: Invoke the navigate() inside your click event

this.router.navigate(['/addposts']);




回答3:


I am assuming you want to navigate to a different page because you want to route to post/addposts. Then you can just change your path to this

{ path: 'post/addposts',component:AddPostComponent}];

I might be wrong and you might want to use multiple router-outlet instead.




回答4:


first install router via: npm install router

import { Routes, RouterModule } from '@angular/router';


export const router: Routes = [
   { path: '',  redirectTo: 'main', pathMatch: 'full'},
  { path: 'main', component:AdminBodyComponent  },
  { path: 'admin', component:AdminComponent  },
  { path: 'posts',component:PostsComponent},
  { path: 'addposts',component:AddPostComponent}];

export const routes: ModuleWithProviders = RouterModule.forRoot(router);
step2:
inject into your .ts file
constructor(
  private router:Router,
  ...
)
step3:
this.router.navigate(['/addposts']);
if you want to use specific router go for this step4:

来源:https://stackoverflow.com/questions/43624102/angular-2-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!