Kun-Yao Lin
250 words
1 minutes
[Angular] #2 Angular Router

How router work in angular#

  1. Focus on these files, we will try to rewrite the content inside then the website can change the page when click !

    1. src/app/app.routes.ts
    2. src/app/app.component.ts
    3. src/app/app.config.ts
    4. src/app/app.component.html
  2. Create the component with angular, remember the angular can use its command to create the new component for the website. Just use the command below.

     ng generate component component-name
    
  3. Imports components and add routes to src/app/app.routes.ts. You can define the path with the component, so link them!

     import { Routes } from '@angular/router';
     import { HomeComponent } from './home/home.component';
     import { ProductsComponent } from './products/products.component';
     export const routes: Routes = [
         { path: '', component: HomeComponent },
         { path: 'products', component: ProductsComponent },
     ];
    
  4. Add imports to Component to src/app/app.component.ts. Same as the before step, but this step is for import routes to the app.

     import { Component } from '@angular/core';
     import { RouterOutlet } from '@angular/router';
     import { CommonModule } from '@angular/common';
     import { SidebarComponent } from './sidebar/sidebar.component';
     @Component({
     selector: 'app-root',
     standalone: true,
     imports: [
         RouterOutlet,
         CommonModule,
         SidebarComponent,
     ], ... 
    
  5. Add router-outlet to app.component.html. Remember to add the router-outlet to the your web application, so the path of page can be auto link to the component.

     <body>
         <div class="router-box">
             <router-outlet></router-outlet>
         </div>
     </body>
    
  6. Modify app.config.ts. The provider can help application correct connect its routes, not only the route inside but also the https client.

     import { ApplicationConfig } from '@angular/core';
     import { provideRouter } from '@angular/router';
     import { routes } from './app.routes';
     import { provideHttpClient } from '@angular/common/http';
    
     export const appConfig: ApplicationConfig = {
     providers: [provideRouter(routes), provideHttpClient()]
     };