ユーザーマニュアル
このマニュアルでは、Angularの主要な機能と使い方について詳しく説明します。コンポーネント、サービス、ルーティング、Directive、pipe、フォームなどについてカバーしています。
コンポーネント開発
コンポーネントの作成
ng generate component user-list
または手動で作成:
import { Component } from '@angular/core';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
styleUrls: ['./user-list.component.scss']
})
export class UserListComponent {
users = ['田中', '佐藤', '鈴木'];
}
テンプレート構文
補間(Interpolation):
<h1>こんにちは、{{ name }}さん</h1>
プロパティバインディング:
<img [src]="imageUrl">
<button [disabled]="isDisabled">クリック</button>
イベントバインディング:
<button (click)="onSave()">保存</button>
双方向バインディング:
<input [(ngModel)]="username">
ライフサイクルフック
| フック | 説明 |
|---|---|
| ngOnInit | コンポーネントの初期化 |
| ngOnChanges | 入力プロパティの変化 |
| ngDoCheck | 変更検出 |
| ngAfterViewInit | ビューの初期化完了 |
| ngOnDestroy | コンポーネントの破棄 |
サービスと依存性注入
サービスの作成
ng generate service user
サービスのコード:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/api/users');
}
}
サービスの使用
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html'
})
export class UserListComponent implements OnInit {
users: User[] = [];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().subscribe(data => {
this.users = data;
});
}
}
ルーティング
ルーターの設定
import { Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'users', component: UserListComponent },
{ path: 'user/:id', component: UserDetailComponent },
{ path: '**', component: NotFoundComponent }
];
ルーターリンク
<nav>
<a routerLink="/home">ホーム</a>
<a routerLink="/users">ユーザー一覧</a>
<a [routerLink]="['/user', userId]">ユーザー詳細</a>
</nav>
ルーターパラメータ
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
this.userId = params['id'];
});
}
ルートガード
import { CanActivate } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
canActivate(): boolean {
return true; // trueを返すとアクセス許可、falseは拒否
}
}
Directive
構造Directive
条件レンダリング:
<div *ngIf="isLoggedIn">おかえりなさい</div>
ループレンダリング:
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
切り替え:
<div [ngSwitch]="status">
<p *ngSwitchCase="'success'">成功</p>
<p *ngSwitchCase="'error'">エラー</p>
<p *ngSwitchDefault>デフォルト</p>
</div>
属性Directive
スタイルクラス:
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">内容</div>
スタイル:
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">内容</div>
Pipe
組み込みPipe
<!-- 日付pipe -->
<p>{{ today | date:'yyyy-MM-dd' }}</p>
<!-- 大文字小文字pipe -->
<p>{{ name | uppercase }}</p>
<p>{{ name | lowercase }}</p>
<!-- 通貨pipe -->
<p>{{ price | currency:'JPY' }}</p>
<!-- 数値pipe -->
<p>{{ pi | number:'1.2-2' }}</p>
<!-- JSON pipe -->
<pre>{{ obj | json }}</pre>
カスタムPipe
ng generate pipe capitalize
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
フォーム処理
Reactive Forms
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class LoginComponent implements OnInit {
loginForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.loginForm = this.fb.group({
username: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(6)]],
remember: [false]
});
}
onSubmit() {
if (this.loginForm.valid) {
console.log(this.loginForm.value);
}
}
}
テンプレート:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<input formControlName="username" placeholder="ユーザー名">
<div *ngIf="loginForm.get('username').touched && loginForm.get('username').errors?.required">
ユーザー名は必須です
</div>
<input type="password" formControlName="password" placeholder="パスワード">
<label>
<input type="checkbox" formControlName="remember"> ログイン状態を保持
</label>
<button type="submit" [disabled]="loginForm.invalid">ログイン</button>
</form>
Template-driven Forms
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<input name="username" [(ngModel)]="username" required #name="ngModel" placeholder="ユーザー名">
<div *ngIf="name.touched && name.errors?.required">ユーザー名は必須です</div>
<button type="submit" [disabled]="form.invalid">送信</button>
</form>
HTTPクライアント
設定
app.module.tsでインポート:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule]
})
export class AppModule {}
リクエスト送信
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
getData() {
this.http.get('/api/data').subscribe(data => {
console.log(data);
});
}
postData() {
this.http.post('/api/data', { name: 'test' }).subscribe();
}
インターセプター
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
const cloned = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(cloned);
};
状態管理
サービスを使った管理
サービスでアプリケーションの状態を管理:
@Injectable({
providedIn: 'root'
})
export class StateService {
private state = new BehaviorSubject<any>(null);
state$ = this.state.asObservable();
updateState(newState: any) {
this.state.next(newState);
}
}
パフォーマンス最適化
遅延読み込み
ルーティングの遅延読み込み:
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
Change Detection
OnPush戦略:
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {}
テスト
ユニットテスト
import { ComponentFixture, TestBed } from '@angular/core/testing';
describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [UserComponent]
}).compileComponents();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
ベストプラクティス
- TypeScriptのstrictモードを使う:strictコンパイルオプションを有効にする
- コンポーネントは小さく специализация:各コンポーネントは1つのことだけをする
- OnPush戦略を使う:変更検出のパフォーマンス向上
- pipeは賢く使う:pipe内で複雑な計算を避ける
- 遅延読み込みを使う:初期読み込み時間を短縮
- テストを書く:コード品質を確保
