Step 1: Make sure you have at least 2 Components
Syarat sah untuk bina routing adalah
- ada sekurang2nya 2 component
- guna cli dibawah untuk generate component baru
ng generate component about
ng g c about
Step 2: Create an app.router.ts file
Kemudian dengan mengunakan editor ( VS e.g ) tepek code dibawahimport { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
export const router: Routes = [
{ path: '', redirectTo: 'about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'services', component: ServicesComponent }
];
export const routes: ModuleWithProviders = RouterModule.forRoot(router);
Tukarkan code2 ini dengan component anda
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ServicesComponent } from './services/services.component';
Ini pula proses selepas import iaitu tentukan kemana component tu hendak dibawa
export const router: Routes = [
{ path: '', redirectTo: 'about', pathMatch: 'full' },
{ path: 'about', component: AboutComponent },
{ path: 'services', component: ServicesComponent }
Step 3: Import the router to app.module.ts
Dah buat syarat tu, untuk membolehkan projek berjaya di build mesti dapat kebenaran dari module.ts
import { routes } from './app.router';letak kat atas
imports: [Jangan lupa letak routes kat bahagian imports, kalau tak dia macam dah siap kerja tapi tak hantar kat lecturer.
BrowserModule,
FormsModule,
HttpModule,
routes
],
Step 4: Add <router-outlet></router-outlet>
di app.component.html, letak:
<router-outlet></router-outlet>
Step 5: Add the routerLink directive
mula letak link kini bukan lagi a href di angular kita guna routerLink kalau dah routing
<ul class="nav navbar-nav">
<li>
<a routerLink="about">About</a>
</li>
<li>
<a routerLink="services">Services</a>
</li>
</ul>
Step 6: Ensure <base href="/"> is in index.html
Kat index jangan lupa letak <base href="/">
dia mewakili routerLink..