Topics covered:
update to version 17
Example file for routing
Lazy loading
Child routes/nesting
To update, go to your Command Prompt terminal.
ng update @angular/core@17.2 @angular/cli@17.2
Once you get updated to angular 17 and check the version (ng version) to make sure, create a new angular project and open in VS Code. The file structure will look like this:
- app.component.html
- app.component.css
- app.component.spec.ts
- app.component.ts
- app.config.ts
No more modules. Now we have standalone components.
I am currently using Angular version 17.2.0. Here is my example code: https://github.com/Deborah-McVey/angular_17_routing_blog/tree/main
My process:
Opened Command Prompt on my computer
cd to folder I want to create new application
ng new angular_17_routing_blog
Selected CSS, Enter
SSR and SSG? N, Enter
Wait for files to be generated:
code angular_17_routing_blog
Will open in Visual Studio Code
package.json will tell what version it is
Open terminal in VS Code with Ctrl+`
ng s -o
will open in browser at http://localhost:4200
Browser will display what is in src/app/app.component.html
"Congratulations! Your app is running."
I’m going to delete everything in app.component.html (Ctrl+a, Delete), and add an h1.
the browser will update.
Ctrl+c in terminal to stop serving, so you can generate components
generate 2 components
ng g c first
ng g c second
app.component.html
set up nav bar with links to components add router outlet at bottom
app.component.ts
add RouterLink and RouterLinkActive
app.routes.ts
add paths without lazy loading yet
it will look like
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent }
ng s to check browser
make sure it works
you can style app.component.css if you want
This is how you change it to lazy loading.
{ path: 'first-component', loadComponent: () => import('./first/first.component').then((c) => c.FirstComponent) },
{ path: 'second-component', loadComponent: () => import('./second/second.component').then((c) => c.SecondComponent) },
Now we can add children to first component.
stop serving, Ctrl+c
generate 2 more components
ng g c child-a
ng g c child-b
go to first.component.html
add h2, links to children, and router outlet
app.routes.ts
add child routes under first component
first.component.ts
you must import RouterOutlet, RouterLink, RouterLinkActive
ng s
References:
https://dev.to/bytebantz/mastering-angular-17-routing-2mf2
VS Code extensions I recommend:
Prettier
Path Intellisense
Be aware:
Angular version 18 was released late May 2024.