How router work in angular
Focus on these files, we will try to rewrite the content inside then the website can change the page when click !
src/app/app.routes.tssrc/app/app.component.tssrc/app/app.config.tssrc/app/app.component.html
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-nameImports 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 }, ];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, ], ...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>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()] };
