[英]In Angular, how to navigate to a relative path with `href`?
I am using Ionic with Angular (ie and @angular/router
), but I believe that this question is also relevant to Angular without Ionic.我将 Ionic 与 Angular (即和
@angular/router
)一起使用,但我相信这个问题也与没有 Ionic 的 Angular 有关。
How can I navigate to a relative folder using href
?如何使用
href
导航到相对文件夹?
I have this structure:我有这个结构:
(root)
..A
....B1
....B2
When I navigate to /A/B1
- the B1
component is rendered.当我导航到
/A/B1
- B1
组件被渲染。 In it, I have this HTML:在其中,我有这个 HTML:
<ios-button href="../B2">Click Me</ios-button>
I expect a button click to navigate to /A/B2
, but instead, it navigates to /B2
.我希望单击按钮导航到
/A/B2
,但相反,它导航到/B2
。
I also tried href="./../B2"
but it gives the same result.我也试过
href="./../B2"
但它给出了相同的结果。
If I use the full path ( href="/A/B2"
) then it works.如果我使用完整路径(
href="/A/B2"
),那么它可以工作。
How do I achieve my expected result with the partial (ie relative) path?如何使用部分(即相对)路径实现我的预期结果?
You have an option to implement it like this, handling redirection inside your Component您可以选择像这样实现它,在组件内处理重定向
More info on Angular's specifying-a-relative-route documentation有关Angular 的指定相对路由文档的更多信息
@Component({...})
export class TestComponent {
constructor(
private router: Router
private route: ActivatedRoute
) {}
navigateTo(path: string): void {
this.router.navigate([path], { relativeTo: this.route });
}
}
With this in place { relativeTo: this.route }
and if you have a path ../B2
, you're telling Angular that from this current route, go 1-step backward and go to B2
有了这个
{ relativeTo: this.route }
并且如果你有一个路径../B2
,你告诉 Angular 从这条当前路线,go 1 步后退和 Z34D1F91FB2E7514B856BA2A B2
Mock Parent Route: http://localhost:4200/parent模拟父路由: http://localhost:4200/parent
Example #1示例 #1
// This will be http://localhost:4200/parent/B2
this.router.navigate(['B2'], { relativeTo: this.route });
Example #2示例 #2
// This will be http://localhost:4200/B2
// As this goes up one level
this.router.navigate(['../B2'], { relativeTo: this.route });
NOTE:笔记:
When dealing with route redirection, it's best to use [routerLink]=""
instead of href
inside your template处理路由重定向时,最好在模板中使用
[routerLink]=""
而不是href
<a [routerLink]="[../B2]">B2</a>
<a [routerLink]="[../B2]">B2</a>
<a [routerLink]="'B2'">B2</a>
with single quote inside<a [routerLink]="'B2'">B2</a>
里面有单引号Or if you'll handle redirection in your component, you'll use Router
from @angular/router
或者,如果您要在组件中处理重定向,您将使用来自
@angular/router
Router
路由器
Have created a Stackblitz Demo for your reference已创建Stackblitz Demo供您参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.