0

I'm working with angular2 rc1. I'm working on a simple game that starts with a menu screen and when clicking on a menu button I would like to navigate to a different view, replacing the current view. I then would like to navigate back with a back button.

This is a seemingly simple requirement, however, all routing samples I see using the router-outlet append to the current view instead of replacing it. e.g.

<h1>Component Router</h1>
 <nav>
  <a [routerLink]="['/crisis-center']">Crisis Center</a>
  <a [routerLink]="['/heroes']">Heroes</a>
 </nav>
<router-outlet></router-outlet>

This markup appends the new view under the </nav> element.

Am I missing something obvious? Is there a simple way to do this or do I need to use the <router-outlet> in combination with an *ngIf to hide the current view?

2 Answers2

1

I was looking for something similar (if I understood correctly your question). My approach (for now) is to wrap the router-outlet inside a div, and change the style (toggle a class would be much better obviously) of that element while the content is loading.

<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/search">Search</a>
</nav>

<div class="loading-overlay" *ngIf="loading">Cargando...</div>

<div [style.display]="loading ? 'none' : 'block'">
  <router-outlet></router-outlet>
</div>

And in the app.component I have this code (credit to @borislemke in this response):

public loading: boolean = true;

constructor(private router: Router) { }

ngOnInit() {
  this.router.events.subscribe((event: any): void => {
    this.navigationInterceptor(event);
  });
}

navigationInterceptor(event): void {
  if(event instanceof NavigationStart) {
    this.loading = true;
  }
  if(event instanceof NavigationEnd) {
    this.loading = false;
  }
}
Community
  • 1
  • 1
Dunos
  • 189
  • 2
  • 13
  • 1
    I'd recommend adding ' || event instanceof NavigationCancel || event instanceof NavigationError' into that second if, to avoid an edge case never ending loading. – S.. Oct 18 '16 at 15:02
0

I don't think there is a other way to do this, you need to use the *ngIf.

What you try to achieve is not the common pattern(the normal pattern is to have a nav menu and a content menu), but it may make sense for a game how you said.

Tiberiu Popescu
  • 4,486
  • 2
  • 26
  • 38