What is angular routing:
- Web applications can have different sections that correspond to different URLs, and supporting those sections programmatically is called routing.
- In Simple words, As per Url, open different angular components is called routing.
URL | Component |
http://localhost:4200/home | Home.component |
http://localhost:4200/aboutus | Aboutus.component |
http://localhost:4200/contactus | ContactUs.Component |
- Package that must be import:
import { Routes, RouterModule } from ‘@angular/Router’;
Example:
Step1 : First Create three components home,aboutus,contactus.
Step2: Configure app.module.ts as follows.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule, Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { Routes, RouterModule } from '@angular/Router'; import { AppComponent } from './app.component'; import { AboutusComponent } from './aboutus/aboutus.component'; import { ContactusComponent } from './contactus/contactus.component'; import { HomeComponent } from './home/home.component'; const AppRoutes: Routes = [ { path: 'about', component: AboutusComponent }, { path: 'Home', component: HomeComponent }, { path: 'ContactUs', component: ContactusComponent } ] @NgModule({ declarations: [ AppComponent, AboutusComponent, ContactusComponent, HomeComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(AppRoutes) ], // Add provider providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step3: Make changes in app.component.ts as follows
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <router-outlet></router-outlet> `, styles: [` p { background-color:silver; font-size : 26px; } `], }) export class AppComponent { }
output: