Angular Navigate Routing between parent and child

1.7k views Asked by At

I have 2 components with parent and child relations. 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.

Routing

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']);
}

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

 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>

Can anybody help me with this, any help is much appreciated.

Thank you.

1

There are 1 answers

0
Jo Carrasco On BEST ANSWER

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 }
];