父子之间的角导航路由

时间:2020-09-27 14:05:13

标签: javascript angular typescript routes angular8

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

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

谢谢。

1 个答案:

答案 0 :(得分:0)

路由器出口是用于渲染组件的标记。您不应将其隐藏。这就像在尝试进入之前先将门关上。如果要“隐藏” 这些元素,则应将路由器插座向上移动在导航层次结构中。这意味着您应该在路由器中创建“要单击的图像页面”和“详细图像页面”的同级。像这样:

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