Hide parent view in angular 2

In the parent component, inject the activated route like so:

class ParentComponent {
  constructor(public route: ActivatedRoute)
  }
}

Now you can use the children property on route to decide whether the current component is the leaf component in the route tree. Together with ngIf, this can be used to hide a part of the view:

<div *ngIf="route.children.length === 0">
  Some content that should only be shown when the user is at the parent component itself.
</div>

<router-outlet></router-outlet>

In the example above, the div will only be shown if the user is on the parent component itself, but not if the user is on a child component.


January 2021

You can remove the component from the parent route. See example here

{
    path: 'parent',
    //component: ParentComponent,
    children: [
      { path : '', pathMatch:'full', component: ParentComponent},
      { path: 'child', component: ChildComponent },
    ],
  }  


The following should do the trick.... not so optimal this solution, but at least it works as you want. So just wrap the things you want to hide inside a div with a boolean value, e.g

<div *ngIf="notSelected">
  <!-- your code here -->
</div>

And just set that boolean to false in the same function where you handle the event of clicking some box in the parent comp.

clicked() {
  ....
  this.notSelected = false;
}

To inform that the parent needs to be shown again when navigating back to parent from child, you can use Subject. So in your parent declare a Subject:

public static showParent: Subject<any> = new Subject();

and in your parent constructor subscribe to changes:

constructor(...) {
  ParentComponent.showParent.subscribe(res => {
     this.notSelected = true; // show parent component
  })
}

and in your child, before navigating back to parent, whatever that event might be:

returnToParent() {
  ParentComponent.showParent.next(false);
  this.router.navigate......
}

Make separate component for the one you called parent (ParentComponent) and for the one you called child (ChildComponent). You can then setup a route that loads either ParentComponent or ChildComponent into a router-outlet in your template. Doing so, the ParentComponent and ChildComponent are at the same route level. You have to change their names to make sense.

Tags:

Angular