Reputation: 9414
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?
Upvotes: 15
Views: 11507
Reputation: 583
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>
Upvotes: 6
Reputation: 9414
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>
Upvotes: 7
Reputation: 11
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.
Upvotes: 0
Reputation: 3015
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.
Upvotes: 35