简体   繁体   English

父子之间的角度导航路由

[英]Angular Navigate Routing between parent and child

I have 2 components with parent and child relations.我有 2 个具有父子关系的组件。 In the parent component, I have images which on click should navigate to child component.在父组件中,我有图像,点击后应该导航到子组件。 Following is my code, the URL in the browser is changing but the page isn't navigating.以下是我的代码,浏览器中的 URL 正在更改,但页面未导航。

Routing路由

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

HTML HTML

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

TS TS

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

The navigation is working only when I use boolean variables to display hide on button click (which is not a good practise), as below.仅当我使用布尔变量在按钮单击时显示隐藏时导航才有效(这不是一个好习惯),如下所示。 Using boolean values after navigating is throwing some problem, on click of back button in child component the parent component is not loading.导航后使用布尔值会引发一些问题,单击子组件中的后退按钮时,父组件未加载。

TS TS

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

HTML HTML

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

Can anybody help me with this, any help is much appreciated.任何人都可以帮助我,非常感谢任何帮助。

Thank you.谢谢你。

The router-outlet is tag used to render the components.路由器出口是用于渲染组件的标签。 You should not hide it.It's like blocking a door before trying to get in. If you want to "hide" the elements, then you should move the router-outlet up in the navigation hierarchy.不应该隐藏它。这就像在试图进入之前挡住一扇门。如果你想“隐藏”元素,那么你应该在导航层次结构中向上移动路由器出口。 What this means is that you should make "Page of Images to Click" and "Page of Detail Image" siblings in the router.这意味着您应该在路由器中创建“要单击的图像页面”和“详细图像页面”兄弟。 Like this:像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM