AngularDartでページ遷移 その1

Categories
Tags
Share

時間を置いてしまったのですが、年末なので多少時間ができたのでDartの勉強を再開しました。 AngularDartでページ遷移をする方法です。

ページ遷移はRoutingで行う

ページ遷移は、Routing(ルーティング)で行います。 ページ遷移というか、一部を書き換えた上で、historyを書き換えていくという感じだと思います。

1. router.dartの読み込み

app_component.dartにて、router.dartのインポートと、アノテーション@Componentで、ROUTER_DIRECTIVESROUTER_PROVIDERSを追記していきます。

import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'package:angular2_components/angular2_components.dart';

@Component(
  selector: 'my-app',
  styleUrls: const ['app_component.css'],
  templateUrl: 'app_component.html',
  directives: const [ROUTER_DIRECTIVES, materialDirectives],
  providers: const [ROUTER_PROVIDERS, materialProviders],
)
class AppComponent {
}

2. html側の設定

index.htmlに、base urlを設定します。

<head>
  <!-- metaタグなど省略 -->
  <base href="/">
  <!-- css読込など省略 -->
</head>

app_component.html側では、ルーティングによる書換領域を指定します。書換領域の指定は、router-outletタグで行います。

<header>
  <h1>Sample</h1>
</header>
<main>
  <router-outlet></router-outlet>
</main>
<footer>footer</footer>

3. 初期表示で使われるコンポーネントの指定

router-outletに最初に表示されるコンポーネントを指定します。app_component.dartにて、アノテーション@RouteConfigで定義します。 初期表示をfirst_componentを定義して使いました。

# 他のは省略
import 'package:sample/first_component/first_component.dart';

@Component(
  # 省略
)
@RouteConfig(const [
  const Route(path: '/', name: 'First', component: FirstComponent, useAsDefault: true),
])
class AppComponent {
}

肝は、useAsDefaultオプションにtrueを渡すところです。

4. ルーティングテーブルに他のコンポーネントを登録

他のコンポーネントを登録します。SecondComponentを登録してみます。@RouteConfigに追記します。

# 他のは省略
import 'package:sample/first_component/first_component.dart';
import 'package:sample/second_component/second_component.dart';

@Component(
  # 省略
)
@RouteConfig(const [
  const Route(path: '/', name: 'First', component: FirstComponent, useAsDefault: true),
  const Route(path: '/second', name: 'Second', component: SecondComponent),
])
class AppComponent {
}

5. htmlにリンクを設置する

ルーティングを定義したものへのリンクは、routerLinkにnameを指定します。 navに追加してみましょう。

<header>
  <h1>Sample</h1>
  <nav>
    <a [routerLink]="['First']">First</a>
    <a [routerLink]="['Second']">Second</a>
  </nav>
</header>
<main>
  <router-outlet></router-outlet>
</main>
<footer>footer</footer>

これでできました。

idを使うようなURLの場合のルーティングに関しては別の記事で書こうと思います。


comments powered by Disqus