【问题标题】:Angular Navigate Routing between parent and child父母和孩子之间的角度导航路由
【发布时间】:2026-01-07 22:50:02
【问题描述】:

我有 2 个具有父子关系的组件。在父组件中,我有单击时应导航到子组件的图像。以下是我的代码,浏览器中的 URL 正在更改,但页面没有导航。

路由

const routes: Routes = [
  {
    path: 'parent', component: ParentComponent, children: [
      { path: 'child', component: ChildComponent}
    ]
  },
  { path: '**', component: LoginComponent }
];

HTML

<section>
    <img src="imagePath" alt="" (click)="gotoProfile()">
</section>
<div>
<router-outlet></router-outlet>
</div>

TS

gotoProfile() {
    this.route.navigate(['/parent/child']);
}

只有当我使用布尔变量显示按钮单击时隐藏(这不是一个好习惯)时,导航才有效,如下所示。导航后使用布尔值会引发一些问题,单击子组件中的后退按钮时父组件未加载。

TS

 gotoProfile() {
      this.hideParentDiv = true;
      this.route.navigate(['/parent/child']);
    }

HTML

 <section *ngIf="hideParentDiv ">
        <img src="imagePath" alt="" (click)="gotoProfile()">
    </section>
    <div *ngIf="!hideParentDiv ">
    <router-outlet></router-outlet>
    </div>

任何人都可以帮助我,非常感谢任何帮助。

谢谢。

【问题讨论】:

  • 首先是关于按钮上的“显示隐藏”的意思。单击按钮或图像时是否隐藏按钮。另外请提供您的路由器模块代码和子组件的一些代码
  • @JoCarrasco 显示并隐藏父组件和子组件,单击图像,因为它应该导航到子组件(因为我遇到导航问题,所以我在这里隐藏父 html)
  • @JoCarrasco 我已经添加了代码

标签: javascript angular typescript routes angular8


【解决方案1】:

router-outlet 是用来渲染组件的标签。你不应该隐藏它。这就像在试图进入之前堵住一扇门。如果你想“隐藏”元素,那么你应该向上移动路由器插座在导航层次结构中。这意味着您应该在路由器中创建“要单击的图像页面”和“详细图像页面”兄弟姐妹。像这样:

const routes: Routes = [
  {
    path: 'home', component: ExampleComponent, children: [
      { path: 'images-page', component: ImagesComponent },
      { path: 'image-detail-page', component: ImageDetailComponent}
    ]
  },
  { path: '**', component: LoginComponent }
];

【讨论】:

    最近更新 更多