1.はじめに
最近ChatGPTに人生相談をするのにはまっています。
今回は、第三弾でAngularの基本的な操作のうちTypeScript ファイル(component.ts)に記述する内容をいくつかまとめていきます。
今回も、Vueの時と同じ作りとしているため、是非こちらと比較してみると分かりやすいと思います。
【Vue.js】Vue.jsって何だろう(値変更に関わるscript編(data()・methods・computed・watch編))
バージョンによって書き方の違いはありますが、Anuglar5での書き方でご紹介します。
2. 基本的な書き方
概要
Angular では、コンポーネントは以下のように構成されます。
htmlファイル・tsファイル・cssファイルの3ファイル構成になります。
app.component.html
<h1 [ngClass]="titleClass">{{ value }}</h1>
<button (click)="pushButton()">
ボタンを押してください!
</button>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root', // HTMLタグの名前
templateUrl: './app.component.html', // HTMLテンプレート
styleUrls: ['./app.component.css'] // スタイルシート
})
// 今回はここに書くことをまとめていきます。
export class AppComponent {
value: string = '';
titleClass: string = 'title';
// ボタンをクリックしたときの処理
pushButton() {
this.value = 'ボタンが押されました!';
}
}
app.component.css
.title {
color: red;
}
今回は下記の概念についてまとめていきます。
| 項目 | 説明 |
|---|---|
| プロパティ | コンポーネントが持つデータ |
| メソッド | ボタン押下などで実行する処理 |
| Getter | データから自動的に計算される値 |
| ngOnChanges / Setter | 値の変化を検知する処理 |
3.解説
①プロパティ
Angularでは、コンポーネントクラス内に定義した変数(プロパティ)が画面で利用するデータになります。たとえば、カウントの数字や入力値など、画面に表示したり処理に使ったりするデータを定義します。
<基本的な書き方>
count = 0;
<テストコード>
sample.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html'
})
export class SampleComponent {
count = 0;
}
sample.component.html
<div>
<h2>カウント:{{ count }}</h2>
<button (click)="count = count + 1">
1増やす
</button>
</div>
最初に表示されるのは count の初期値であるため、「カウント:0」が表示されます。
ボタンをクリックすると count が増加し、「カウント:1」「カウント:2」…と変化します。
②メソッド
メソッドとは、Angularコンポーネントでイベントに応じて実行したい処理を書く場所です。
ボタンを押したときやデータを加工したいときに利用します。
<基本的な書き方>
メソッド名() {
// 実行したい処理
}
<テストコード>
sample.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html'
})
export class SampleComponent {
count = 0;
addCount() {
this.count++;
}
}
sample.component.html
<div>
<h2>カウント:{{ count }}</h2>
<button (click)="addCount()">
1増やす
</button>
</div>
最初は「カウント:0」が表示されます。
ボタンをクリックすると addCount() が実行され、count の値が増加するため、「カウント:1」「カウント:2」…と変化します。
③Getter(computed相当)
AngularにはVueの computed のような機能はありませんが、Getter を利用することで同様のことが実現できます。
Getterは、プロパティの値をもとに計算結果を返すための仕組みです。
<基本的な書き方>
get プロパティ名() {
return 計算結果;
}
🔍メソッドとの違い
Getterは画面側で通常の変数と同じように扱えます。
{{ fullName }}
のように記述できるため、Vueのcomputedに近い使い方ができます。
<テストコード>
sample.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html'
})
export class SampleComponent {
firstName = '山田';
lastName = '太郎';
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
sample.component.html
<h2>firstName:{{ firstName }}</h2>
<h2>lastName:{{ lastName }}</h2>
<h3>
フルネーム(Getter):{{ fullName }}
</h3>
初期表示では firstName と lastName を組み合わせた「山田 太郎」が表示されます。
firstName または lastName を変更すると、自動的に fullName の表示も更新されます。
④値の変化を検知する処理
Vueのwatchに完全に対応する機能はAngularにはありません。
用途によって以下を使い分けます。
- @Input() の監視 → ngOnChanges
- フォーム入力の監視 → valueChanges
- プロパティ変更時の処理 → Setter
今回はSetterを利用した例を紹介します。
<基本的な書き方>
private _value = '';
set value(val: string) {
this._value = val;
// 値変更時の処理
}
get value() {
return this._value;
}
<テストコード>
sample.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html'
})
export class SampleComponent {
private _keyword = '';
log = '';
get keyword() {
return this._keyword;
}
set keyword(value: string) {
const oldValue = this._keyword;
this._keyword = value;
this.log =
`入力が変わりました:「${oldValue}」→「${value}」`;
}
}
sample.component.html
<input [(ngModel)]="keyword">
<p>入力内容:{{ keyword }}</p>
<p>ログ:{{ log }}</p>
keyword に文字を入力するたびに Setter が呼ばれ、変更内容が log に記録されます。
たとえば「abc」と入力すると、ログには
入力が変わりました:「ab」→「abc」
のように表示されます。
4.さいごに
今回はAngularの component.ts に記述する代表的な内容として、
- プロパティ
- メソッド
- Getter
- Setter
を紹介しました。
Vueの data・methods・computed・watch と比較すると、
| Vue | Angular |
|---|---|
| data | プロパティ |
| methods | メソッド |
| computed | Getter |
| watch | ngOnChanges / valueChanges / Setter |
という対応関係になります。
次回は Angular のライフサイクルフック(ngOnInit、ngOnChanges、ngOnDestroy など)についてまとめていきたいと思います。






