How do I navigate to a sibling route?

▼魔方 西西 提交于 2019-11-27 12:17:32
Harry Ninh

If you are using the new router (3.0.0-beta2), you can use the ActivatedRoute to navigate to relative path as follow:

constructor(private router: Router, private r:ActivatedRoute) {} 

///
// DOES NOT WORK SEE UPDATE
goToContact() {
  this.router.navigate(["../contacts"], { relativeTo: this.r });
}

Update 08/02/2019 Angular 7.1.0

current route: /department/7/employees/45/sales

the old version will do: /department/7/employees/45/sales/contacts

As per @KCarnaille's comment the above does not work with the latest Router. The new way is to add .parent to this.r so

    // Working(08/02/2019) 
    goToContact() {
       this.router.navigate(["../contacts"], { relativeTo: this.r.parent });
    }

the update will do: /department/7/employees/45/contacts

The RouterLink directive always treats the provided link as a delta to the current URL:

[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']"     // or
[routerLink]="['child']" 

// with route param     ../sibling;abc=xyz
[routerLink]="['../sibling', {abc: 'xyz'}]"
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
[routerLink]="['../sibling']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

The navigate() method requires a starting point (i.e., the relativeTo parameter). If none is provided, the navigation is absolute:

constructor(private router: Router, private route: ActivatedRoute) {}

this.router.navigate("/absolute/path");
this.router.navigate("../../parent", {relativeTo: this.route});
this.router.navigate("../sibling",   {relativeTo: this.route});
this.router.navigate("./child",      {relativeTo: this.route}); // or
this.router.navigate("child",        {relativeTo: this.route});

// with route param     ../sibling;abc=xyz
this.router.navigate(["../sibling", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../sibling?p1=value1&p2=v2#frag
this.router.navigate("../sibling", {relativeTo: this.route, 
    queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});

// RC.5+: navigate without updating the URL 
this.router.navigate("../sibling", {relativeTo: this.route, skipLocationChange: true});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!