angular2の@angular/routerを用いて、ページ遷移をするためのrouting設定をする
angular2のrouterを用いて、ページ遷移ができるようにする
今日は、こんな感じの簡単なroutingを実現してみたいと思います。
0. 準備
新規プロジェクトを作成し、サーバをスタートさせます。
ng new angular-router ng serve
1. app.component.htmlの編集
以下のように編集します。
<h1>{{title}}</h1> <nav> <a routerLink="/first">1ページ目へ</a> <a routerLink="/second">2ページ目へ</a> </nav> <router-outlet></router-outlet>
<router-outlet>にそれぞれのページの内容が出力されます。
2. それぞれのページ用コンポーネントを生成
ng g component first-page ng g component second-page
3. app.moduleにRouterModuleとRoutesをimport。各々のcomponentもimport。
// src/app/app.module.ts // routing用のmodule import { RouterModule, Routes } from '@angular/router'; // 各ページを表示させるためのコンポーネント import { FirstPageComponent } from './first-page/first-page.component'; import { SecondPageComponent } from './second-page/second-page.component';
4. app.moduleのimportsにRouterModuleを追加し、routingの設定をjson配列で書き込む
// src/app/app.module.ts @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, // -- ここから -- RouterModule.forRoot([ {path: "first", component: firstPageComponent }, {path: "second", component: secondPageComponent } ]) // -- ここまで追加 -- ], providers: [], bootstrap: [AppComponent] })
routingの設定は、
{ path: "routingのパス", component: "使用component"}
の配列で指定することが出来ます。
結果