Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 prevent router-outlet from reloading parent component

Tags:

angular

Inside my app.component.html I have the following code:

<div class="container-fluid">
  <router-outlet></router-outlet>
</div>

When I enter in http://localhost:4200 it loads the AppComponent (no problems so far), but when I enter in http://localhost:4200/success (which loads another route) it reloads AppComponent.

How can I prevent Angular from reloading my AppComponent when I navigate to other routes?

app-routing.module

const routes: Routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
  { path: 'success', component: SuccessComponent },
  { path: 'error', component: ErrorComponent },
];
like image 855
brazuka Avatar asked May 17 '26 01:05

brazuka


1 Answers

Expanding on what @Efe said in the comments.

When you input a route into the url, it reloads the entire app, no matter what, as it thinks this is a new web page. To get it to load you need to navigate inside your app.

You can navigate in multiple ways, each having benefits depending on your particular setup.

RouterLink is beneficial if you have a navigation pane, especially if you have a parent layout component, as it is relative to that component, making nested navigation much simpler.

Router Navigate is the primary way to do it inside the component, and is often the more common method to navigate. With it you can do absolute or relative routing, though relative tends to be more complex.

You may be able to find more information at here if needed.

Avoid using window.url or the like to navigate, as that is the same as inputting a url into the url bar, and will reload the app.

like image 145
Joo Beck Avatar answered May 20 '26 02:05

Joo Beck