Angular 2 で Passive Link を活用してシンプルで分かりやすいコードを書く
Angular 2 での Passive Link とは?
主な違い:
- クリック時にページ遷移が発生しない
- ルーティングロジックを記述する必要がない
- 単に DOM 要素の状態を変更する
使用例:
- メニュー項目のハイライト
- ボタンの活性化/非活性化
- コンテンツの表示/非表示切り替え
メリット:
- コード量が減る
- シンプルで分かりやすい
- テストが容易
- ページ遷移には使用できない *複雑なロジックには不向き
Passive Link の実装:
@angular/router
モジュールをインポートするRouterLink
ディレクティブを使用するrouterLinkActive
ディレクティブを使用する (オプション)
例:
<a routerLink="/home">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
上記の例では、
/home
へのリンクをクリックすると、Home
コンテンツが表示されます。/about
へのリンクをクリックすると、About
コンテンツが表示され、active
クラスが追加されます。
補足:
- Passive Link は Angular 2 の Router モジュールの機能の一つです。
- Passive Link は、ページ遷移を伴わないリンクを作成するために使用されます。
- Passive Link は、コード量を減らし、シンプルで分かりやすいコードを書くために役立ちます。
関連キーワード:
- Angular
- Routing
- RouterLink
- routerLinkActive
Angular 2 Passive Link サンプルコード
app.component.html:
<h1>Passive Link サンプル</h1>
<ul>
<li><a routerLink="/home">Home</a></li>
<li><a routerLink="/about" routerLinkActive="active">About</a></li>
<li><a routerLink="/contact">Contact</a></li>
</ul>
<router-outlet></router-outlet>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent { }
<h1>Home</h1>
<p>Home コンテンツ</p>
<h1>About</h1>
<p>About コンテンツ</p>
<h1>Contact</h1>
<p>Contact コンテンツ</p>
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent },
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
実行方法:
npm install
を実行して必要なモジュールをインストールします。ng serve
を実行してサーバーを起動します。- ブラウザで
http://localhost:4200
を開きます。
動作確認:
- ナビゲーションバーのリンクをクリックして、各ページに移動することを確認します。
/about
ページに移動した際に、About
リンクにactive
クラスが付与されていることを確認します。
- このサンプルコードは、基本的な Passive Link の使用方法を示しています。
- より複雑なロジックを実装するには、コンポーネントクラスのコードを変更する必要があります。
Angular 2 で Passive Link を実装する他の方法
<a routerLink="/home" (click)="doSomething()">Home</a>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
doSomething() {
// 何か処理を行う
}
}
Router サービスの navigate() メソッド:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.navigate(['/home']);
}
}
カスタムディレクティブ:
<a myPassiveLink="/home">Home</a>
import { Directive, ElementRef, HostListener } from '@angular/core';
import { Router } from '@angular/router';
@Directive({
selector: '[myPassiveLink]'
})
export class PassiveLinkDirective {
constructor(private elementRef: ElementRef, private router: Router) {}
@HostListener('click', ['$event'])
onClick(event: Event) {
event.preventDefault();
this.router.navigate([this.elementRef.nativeElement.getAttribute('myPassiveLink')]);
}
}
- シンプルなリンクの場合は、
routerLink
ディレクティブのみで十分です。 - 何か処理を行う必要がある場合は、
routerLink
ディレクティブとclick
イベントリスナーを組み合わせる必要があります。
angular routes angular2-routing