Friday, 20 October 2017

Angular simple routing example

Let's create a new project:


Then let's create two components: intro and body:
cd routing
ng generate component intro
ng generate component body
npm start
view raw create_comps hosted with ❤ by GitHub
Let's update the template app.component.html:
<h1>Switching between pages</h1>
<a routerLink="intro">Intro</a> <!-- The link to the intro component !-->
<a routerLink="body">Body</a> <!-- The link to the body component !-->
<router-outlet></router-outlet> <!-- The place where to display the component !-->
And the module file app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { IntroComponent } from './intro/intro.component';
import { BodyComponent } from './body/body.component';
import { RouterModule } from "@angular/router";
@NgModule({
declarations: [
AppComponent,
IntroComponent,
BodyComponent
],
imports: [
BrowserModule,
RouterModule.forRoot([
{path: 'intro', component: IntroComponent},
{path: 'body', component: BodyComponent},
{path: '', redirectTo: '/intro', pathMatch: 'full'}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
view raw app.module.ts hosted with ❤ by GitHub
Done! Now we can switch between the two components:


No comments:

Post a Comment