Angular 在父子之间导航路由

Angular Navigate Routing between parent and child

我有 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>

任何人都可以帮我解决这个问题,非常感谢任何帮助。

谢谢。

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

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