AngularとTypeScriptでSPAを作成する
前提
| 項目 | バージョン |
|---|---|
| OS | Windows10 |
| node | v18.16.0 |
VS Codeが「VS Live Share」なんて便利なものを出してきたのでペアプログラミングができるし、エディタはVS Codeを使いましょう。
nodeはnodist(nvmのほうが良いかも)でとりえずインストールします。node8.9以上を使用しましょう。
Angular CLIをインストールする
AngularはTypeScriptを採用しています。静的型付けのJSなので素敵です。
では、Angular CLIをグローバルインストールします。
C:\>npm install -g @angular/cli
バージョン確認
ngコマンドでバージョン確認します。
C:\>ng version
? Would you like to share pseudonymous usage data about this project with the Angular Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more
details and how to change this setting, see https://angular.io/analytics. Yes
Thank you for sharing pseudonymous usage data. Should you change your mind, the following
command will disable this feature entirely:
ng analytics disable --global
Global setting: enabled
Local setting: No local workspace configuration file.
Effective status: enabled
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 16.0.2
Node: 18.16.0
Package Manager: npm 9.5.1
OS: win32 x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.1600.2 (cli-only)
@angular-devkit/core 16.0.2 (cli-only)
@angular-devkit/schematics 16.0.2 (cli-only)
@schematics/angular 16.0.2 (cli-only)
プロジェクト作成
次にAngularプロジェクトを作成します。
C:\>ng new プロジェクト名
今回はプロジェクト名はappsとしました。
C:\>ng new apps ... ✔ Packages installed successfully.
これでプロジェクト作成に成功しました。
サーバを起動してみます。
C:\>cd apps C:\apps>ng serve --open ? Would you like to share pseudonymous usage data about this project with the Angular Team at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more details and how to change this setting, see https://angular.io/analytics. No
これでhttp://localhsot:4200/でウェルカムページがオープンします。(--openをつけると強制的にブラウザ起動します)
プロジェクトルート/src/app配下に以下ファイルが作成されます。ルートコンポーネントになります。
| ファイル | 補足 |
|---|---|
| app.component.ts | |
| app.component.css | |
| app.component.html | |
| app.component.ts | |
| app.module.ts | standaloneでは存在しない |
src/app/app.module.ts(standaloneでは存在しないファイル)
ルートコンポーネントにだけこのファイルがあります。使用するモジュールを宣言するファイルで、中身の内容は以下のとおりです。
| キー | 内容 |
|---|---|
| declarations | コンポーネント名 |
| imports | Angularのモジュール |
| providers | サービスなどのモジュール |
| bootstrap | 一番最初に起動されるコンポーネント |
src/index.html
index.htmlがメインのhtmlファイルとなります。ほとんど修正することはないと思いますが、タイトルぐらいは修正したりするかもしれません。
src/style.css
この位置にあるstyle.cssは、全てのアプリに影響を与えたい場合に記述します。
ルートコンポーネントを修正してみます。
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
msg = 'あ'; // 追加
}
msgという変数を追加しました。この変数はhtmlファイル内で、{{msg}}として使うことができます。
app.component.html(一部)
<h1>
Welcome to {{ title }}! {{msg}} <!-- 追加 -->
</h1>
ファイルを変更して保存したらホットデプロイされるので再起動は不要です。
コンポーネントを作成する
コンポーネントを作成すると、ルートコンポーネント配下にコンポーネントが作成されます。
コンポーネントを作成するには
C:\>ng generate component コンポーネント名
と実行します。コンポーネント名を「abc」とすると、src – app – abcというディレクトリが作成されます。
abcディレクトリ内には以下ファイルが作成されます。
| ファイル |
|---|
| abc.component.css |
| abc.component.html |
| abc.component.spec.ts |
| abc.component.ts |
コンポーネントは早い話がHTMLのカスタムタグだと思います。abcなら<app-abc></app-abc>って感じでしょうか。
タグのプレフィックスであるappはangular.jsonで指定されていますので、変更したい場合はangular.jsonを修正すればタグのプレフィックスを修正することができます。
これも試しにルートコンポーネントのapp.components.htmlを修正してみます。
<h1> Welcome to {{ title }}!
<app-abc></app-abc>
描画します。
コンポーネント名.component.tsファイル
コンポーネント名を「abc」とするとこのファイルの中身は以下のようになります。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-abc',
templateUrl: './abc.component.html',
styleUrls: ['./abc.component.css']
})
export class AbcComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
OnInitとは
OnInitとは、ngOnInitメソッドを持つインタフェースのようです。ngOnInitメソッドは、コンポーネントが作られた後に呼び出されます。
import { OnInit } from '@angular/core';
export interface OnInit {
ngOnInit(): void;
}
app.module.tsに自動的にコンポーネントが追加される(standaloneでは存在しないファイル)
ng generateコマンドでコンポーネントを追加すると、app.module.tsファイルに自動でコンポーネントが追加されるので、手動で追加が不要になります。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AbcComponent } from './abc/abc.component';
@NgModule({
declarations: [
AppComponent,
AbcComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
カスタムタグ(コンポーネント)に属性をつける@Input
コンポーネントに属性を付けることができます。
C:\>ng generate component dell
dellというコンポーネントを作成したとします。
dell.component.tsファイルを編集します。
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-dell',
templateUrl: './dell.component.html',
styleUrls: ['./dell.component.css']
})
export class DellComponent implements OnInit {
constructor() { }
@Input() alt; // 追加
@Input() src; // 追加
ngOnInit() {
}
}
この2行だけを追加します。これでalt属性とsrc属性を使用することができます。
次にdell.component.htmlを編集します。
<span>{{alt}} - {{src}}</span>
わかりやすく属性を表示するだけです。
ルートコンポーネントのapp.component.htmlに以下の1行を追加しましょう。
<app-dell alt="ここがalt属性" src="ここがsrc属性"></app-dell>
以下のようにレンダリングされます。
定数クラスを定義する
Constクラスみたいなのを定義しておくと便利だと思います。
src – app配下にconst.component.tsファイルとして保存します。
export class Const {
id: number;
name: string;
}

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^








コメント