Admir Sabanovic
Admir Sabanovic

Reputation: 655

Angular2 rc1 router navigate by url

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.

Upvotes: 1

Views: 12445

Answers (3)

Pardeep Jain
Pardeep Jain

Reputation: 86730

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

Upvotes: 6

Caleb Williams
Caleb Williams

Reputation: 1065

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');
}

Upvotes: 1

Shailesh  kala
Shailesh kala

Reputation: 1852

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']);

Upvotes: 0

Related Questions