1

I have parent component with url /app when I enter enter into that component, by default following component is loaded with following routes:

@Routes([
   { path: '/users', component: UserComponent },
   { path: '/other', component: OtherComponent }
])

and I am implementing OnInit interface:

ngOnInit() {
    this.router.navigate(['users'], this.currSegment);
}

Since parent route is /app and child is implementing ngOnInit I can navigate to users, but if I want directly to navigate through url to route /other it is impossible.

2
  • which router are you using, router or router-deprecated May 16, 2016 at 13:01
  • excuse me, I forgot to mention. it is router May 16, 2016 at 14:22

3 Answers 3

6

There are two methods availabel for the same

  • router.navigate(['.....'])
  • router.navigateByUrl('.....')

if your going to use first one than you can use like this

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

which accepts array with route name

and in second case you have to pass string as parameter like this

this.router.navigateByUrl('/app/users');

passing parameter

if you want to send routing parameter along with routing than you can use like this

this.router.navigateByUrl('/app/users/'+id);

where id is your data/key whatever

see also

1

You need to declare your @Route params:

@Route([
  { path: '/users/:id', component: UsersComponent }
])
export class MyComponent implements OnInit {
  constructor(private router: Router) {}
  ngOnInit() {
    // assuming this.userId comes from somewhere
    this.router.navigate(['/users/', this.userId]);
  }
}

If you need to access your params, you can use RouteSegment in your constructor:

constructor(private segment: RouteSegment) {
  this.userId = segment.getParam('id');
}
0

In angular2 rc1 there is no name parameter for routes any more, you now have to use the following code to navigate to a different page

this._router.navigate(['/users']);

1
  • How can I navigate to a sub-route like /users/:id with the navigate command?
    – hmrc87
    Jun 7, 2016 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.