12

All,

I would like to use *ngIf to remove a section of a page if a specific router-outlet has a component.

I've tried searching through ActivatedRoute and Router, but I can't seem to figure it out. How do you check if a specific router-outlet is in use?

Dan Grahn
  • 9,044
  • 4
  • 37
  • 74

4 Answers4

32

Can be solved like this:

<div [hidden]="!myOutlet.isActivated">
  <router-outlet name="my-outlet" #myOutlet="outlet"></router-outlet>
</div>

No changes in component class needed.

martsraits
  • 2,915
  • 3
  • 27
  • 25
  • Why can't I do like this----html : ts:@ViewChild('myOutlet') myOutlet: RouterOutlet .When I want to use myOutlet, it's a nativeElement, not an RouterOutlet – fbfatboy Dec 01 '20 at 01:48
4

I figured this out. You need to use the events for router outlets. However, you can't use ngIf because events won't be fired unless the outlet is in the dom.

ts

showOutlet: boolean;

onActivate(event : any) {
  this.showOutlet = true;
}

onDeactivate(event : any) {
  this.showOutlet = false;
}

html

<div [hidden]="!showOutlet">
  <router-outlet name="my-outlet"
      (activate)="onActivate($event)"
      (deactivate)="onDeactivate($event)"></router-outlet>
</div>
Gustavo Santamaría
  • 837
  • 1
  • 10
  • 21
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
  • out of curiosity what is the use-case when you would hide a `router-outlet`? – Sonu Kapoor Dec 08 '17 at 14:39
  • I have an interface using Project Clarity. Sometimes I want to use the side-nav (dashboard), other times I want to use the sub-nav (search). I have each section set up as a different router-outlet to separate concerns. – Dan Grahn Dec 08 '17 at 17:15
1

to check whenever OUTLET is in use, try this one:

<router-outlet #outlet="outlet"></router-outlet>

<div *ngIf="!outlet.isActivated">Outlet is EMPTY!</div>
<div *ngIf="outlet.isActivated">Outlet is in use!</div>
0

It is possible to get this information from the Angular Router.

As of version @angular/core: 7.2.0.

html:

<router-outlet name="myOutlet"></router-outlet>

ts of any component file:

export class MyComponent {

    constructor(
        router: Router
    ) {}

    ngOnInit(): void {
        const myOutletIsActive: Observable<boolean> = this.router.events.pipe(
            filter((event: RouterEvent) => event instanceof NavigationEnd),
            map(() => this.router.getCurrentNavigation()
                .extractedUrl.root.children.primary.children.myOutlet !== undefined)
        );
        myOutletIsActive.subscribe(isActive => console.log('isActive', isActive));
    }   
}

The advantage is that you can retrieve the state of every outlet from every component of your app.

pschulzk
  • 11
  • 3