简体   繁体   中英

Angular routing displaying the same app.component.html

I'm currently using Angular version 13.

As stated by the official documentation, routing should be done by creating a component and routing it like this in the app-routing.module.ts

const routes: Routes = [
{ path: 'first-component', component: 
FirstComponent },
{ path: 'second-component', component: 
SecondComponent },
];

but doing so will render my app.comoponent.html file without actually changing anything. I can see that the url changed, but that's about it. Other newer sources consider doing something like

{
path:'mainpage',
loadChildren: () => import('./mainpage/mainpage.module').then(m 
=> m.MainpageModule)
}

and, as the solution above, does not work for me. I've also added the <router-outlet></router-outlet> directive, (which was actually already added) but nothing changed. What is currently happening? Thanks!

The RouterOutlet Acts as a placeholder that Angular dynamically fills based on the current router state so in most cases you'll probably have the <router-outlet></router-outlet> directive in your app.component.html. This element actually informs Angular to update the application view with the component for the selected route.

Each route in routes array is a JavaScript object which contains two properties. The first property is the path which defines the URL path for the route. The second one is the component which defines the component Angular should use for the corresponding path.

loadChildren is a different issue. By default, Angular NgModules are eagerly loaded, which means that as soon as the application loads, so does all of the NgModules , even if they are not immediately necessary. If you wish to use lazy loading for Angular modules, you can use the loadChildren (instead of component like in your first example) in your AppRoutingModule routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM