【Angular】環境構築 - ChuN6868/CodeChrysalis-fullstuck-project GitHub Wiki

前提

下記のバージョンを用いる

image

npmのインストールは現在選択しているnodeにインストールされる。
つまり、nvmを用いてnodeのバージョンによって異なったangular/cliのバージョンをグローバルインストールすることでバージョンの切り替えが可能となる。
例)

nvm install 20.18.0
nvm install 22.14.0
// nodeのバージョンを指定してインストール

nvm ls
// インストールしたnodeの一覧が表示される

nvm use 20.18.0
// nodeのバージョン切替

npm install -g @angular/[email protected]
// v20のnodeにグローバルインストール
// ここで一度シェルを再起動

ng version
// angular/cliのバージョンとnodeのバージョンが表示される(20.18.0と18.2.12が表示)

nvm use 22.14.0
// nodeのバージョン切替

npm install -g @angular/cli
// 最新バージョンがv22系のnodeにグローバルインストール

ng version
// 最新のangular/cliが表示される

環境構築

Angularプロジェクト作成

npm install -g @angular/cli
// Angular CLIをグローバルインストール(初回のみ必要)

ng new <プロジェクト名> --standalone
// --standaloneフラグを付けることで、従来のAppModuleを使わずに、コンポーネント単体で動かすモダン構成になる
// この構成はAngular v17以降の推奨構成
// スタイルシートはCSS、Server-Side RenderingはNoを選択

cd <プロジェクト名>
ng serve
// angularアプリの起動

ホーム画面の作成+ルーティング設定(画面遷移)

下記コマンドでファイルを生成

ng generate component pages/home --standalone
ng generate component pages/K01 --standalone
// 画面を作成する際は"pages/"配下に配置
// 複数画面で再利用するパーツは"components/"配下に配置

src/app/app.component.tsの中身を下記のように修正

import { Component } from '@angular/core';
import { RouterLink,RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterLink,RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})

export class AppComponent {
  title = 'address-app';
}

src/app/app.routes.tsを下記のように修正

import { Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { K01Component } from './pages/k01/k01.component';

export const routes: Routes = [
    { path: '', component: HomeComponent},
    { path: 'page1', component: K01Component}
];

src/app/app.component.htmlを下記のように修正

<nav>
  <a routerLink="/">Home</a> |
  <a routerLink="/page1">Page1</a>
</nav>
<hr />
<router-outlet></router-outlet>

これでの箇所がルーティング設定したコンポネントにパス次第で切り替わるようになる。

ng serve

追加機能

HttpClient関連(API叩くとき)

①src/app.config.tsを下記のように修正

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes), // ルーターの定義
    provideHttpClient() // APIを使用する際に必要
  ]
};

②src/app/pages/home/home.component.tsに下記のコードを追記

import { Component, OnInit } from '@angular/core'; // 追加箇所
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http'; // 追加箇所

@Component({
  selector: 'app-home',
  imports: [CommonModule, FormsModule],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})

// 追記箇所
export class HomeComponent {
  expresswords: string = '';
  error: string = '';

  constructor(private http: HttpClient) {}

  // ngOnInitは画面リロード時に実行されるもの
  ngOnInit(): void {
    this.initTest();
  }

  // ngOnInitで実行する関数(APIあり)
  initTest() {
    const url = `http://localhost:5000/api/init`;
    this.http.get<any>(url).subscribe({
      next: (res) => {
        console.log(res.message);
        this.expresswords = res.message;
      },
      error: () => {
        this.error = 'API通信に失敗';
      }
    })
  }

  // ボタンを押した際に実行する関数(APIあり)
  test() {
    const url = `http://localhost:5000/api/hello`;
    this.http.get<any>(url).subscribe({
      next: (res) => {
        console.log(res);
        console.log(res.message);
        this.expresswords = res.message;
      },
      error: () => {
        this.error = 'API通信に失敗';
      }
    })
  }
}

③src/app/pages/home/home.component.htmlを下記のように修正

<h1>ホーム画面</h1>
<p>ここでバックエンドとの通信を試みる</p>
<button (click)="test()">バックエンドテスト</button>
<div>
    <p>{{ expresswords }}</p>
</div>
⚠️ **GitHub.com Fallback** ⚠️