Carli Beeli
Carli Beeli

Reputation: 810

Angular change Route but keep navigation as is

Angular is built for Single Page Applications, so it should be possible to change the route but only have certain elements in the browser window changed, right?

For example I have a simple page with a main navigation component and a content area component.

Would it be possible to navigate to a different route and keep the main navigation component untouched?

Currently, when I do navigate to a different route, the main navigation component is always reloaded (OnInit is fired).

Any thoughts?

Thanks a lot!

Upvotes: 0

Views: 914

Answers (1)

trungvose
trungvose

Reputation: 20034

Seem you have embedded the main navigation component into another components that is assigned to different route. What I can suggest is If you have a shared navigation for every page, keep it in the app.component with the same level with router-outlet. Just like the official example from Angular team.

So when you change the route, it will only affect the router-outlet. Your main-navigation will be init only one time.

main-navigation.component.ts

@Component({
  selector: 'main-navigation',
  template: `
    <nav>
      <a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
      <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
    </nav>
  `
})

export class MainNavigationComponent {

}

app.component.ts

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <main-navigation></main-navigation>
    <router-outlet></router-outlet>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Tour of Heroes';
}

Upvotes: 1

Related Questions