javascript - Angular 路由器如何从父组件调用子组件

标签 javascript angular typescript routes

我有以下路线-

const routes: Routes = [
    {
        path: '',
        component: ParentComponent,
        children: [
            {
                path: ':id',
                component: ChildComponent,
            },
        ]
    }
];

在父级的构造函数中,我想导航到某个 id,例如“test”。 我试过这个-

constructor(private router: Router) {
    this.router.navigate(['child']);
}

还有这个-

constructor(private router: Router) {
    this.router.navigate(['/child']);
}

还有这个-

constructor(private router: Router) {
    this.router.navigate(['./child']);
}

还有这个-

constructor(private router: Router) {
        this.router.navigate(['../child']);
    }

我的网址是 - http://localhost:4200/parent .

但所有这些选项我都会转到 http://localhost:4200/child而不是http://localhost:4200/parent/child

知道为什么吗?我怎样才能使它相对于父级?

最佳答案

因为navigate采用绝对路径。

你必须明确地告诉它是相对的:

constructor(
  private router: Router,
  private route: ActivatedRoute
) {
  this.router.navigate(['child'], { relativeTo: this.route });
}

关于javascript - Angular 路由器如何从父组件调用子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283560/

相关文章:

javascript - 在嵌套层次结构中向上移动值,直到键不再命名为 '_ignore'

javascript - provide 函数获取的参数到底是什么?

Angular NGX 图表 : adjust X tick number

javascript - 窗口完全加载的 setTimeout 的最佳替代是什么?

javascript - 如何检查值属于 JSON 中的某个区间

javascript - 通过 Javascript 获取表格单元格的坐标并与不同表格进行比较

Angular 自定义管道参数

angular - 将参数传递给组件。是否使用括号

typescript - 在 super() 调用中访问它

reactjs - 观察者无法与 useLocalObservable 一起使用