Reputation: 1051
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 },
];
Upvotes: 3
Views: 5569
Reputation: 1913
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.
Upvotes: 1
Reputation: 12036
From Angular.io The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. The order should be:
routes with a static path,
empty path route, that matches the default route.
wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.
Changing the order will fix the issue:
const routes: Routes = [
{ path: 'success', component: SuccessComponent },
{ path: 'error', component: ErrorComponent },
{ path: '', pathMatch: 'full', component: HomeComponent },
];
Upvotes: 1