当サイトは、アフィリエイト広告を利用しています
プロジェクトでAngularを扱ったのでの次使う時にスムーズに理解できるように
ルートモジュールの使い方と基本的な仕組みをまとめて残しておく。
angularの基本的な仕組みをプロジェクト生成時に
作成されるファイルからまとめる。
今回まとめるangularの基本となるルートモジュールのついては下記の書籍も
参考にしています。
もし業務ではじめてAngularを触るなら、一度読んでおいて損はないと思います!
Angularを使うために下記をインストールする必要がある。
node.jsについてはnode.jsをそのままインストールしてもいいが、
node.jsのversionを管理できるNVMを使うのがおすすめ。
NVMのインストール方法と使い方については下記記事で紹介しています。
Angular ClIについてはyarnでグローバルインストールしてもうまくできなかったため
npmを使った方がいいっぽい。
※ng: command not foundっていわれる
npm i -g @angular/cli
vscodeやターミナルで下記で作成できる
ng new Angular_app
プロジェクトを作成と同時に作成されるファイルを元に
Angularの仕組みをまとめていく
プロジェクト生成時に下記の3つのファイルが自動生成される
起動時の流れとしては
main.tsでコンポーネント等がまとめられてルートモジュール(AppModule)を読み込み
index.htmlに表示させるイメージ
トップページのhtml。
プロジェクト生成時にsrc配下に自動生成される。
重要なのは< app-root >でこの部分が
main.tsでbootstrapModuleされているmodule内で
bootstrapされてるコンポーネントに置き換わって表示される
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Angular</title><base href="/"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" type="image/x-icon" href="favicon.ico"></head><body><app-root></app-root></body></html>
アプリを起動するためのスタートアップコード。
index.htmlと同じで自動生成され、src配下に格納される。
app.module.tsを読み込みbootstrapModuleで起動する。
起動時にindex.htmlの< app-root >に表示するコンポーネントは
app.module.ts内のbootstrapで設定する。
import { enableProdMode } from "@angular/core";import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";import { AppModule } from "./app/app.module";import { environment } from "./environments/environment";if (environment.production) {enableProdMode();}platformBrowserDynamic()//起動するモジュールを設定.bootstrapModule(AppModule).catch(err => console.log(err));
angularのモジュールはアプリを構成する
をまとめたもののことであり
app.module.tsの中で@NgModuleデコレーターを
をつけてangularのモジュールとして定義している。
エントリーポイント(src/main.ts)により呼び出される
※javascriptのモジュールとは別なので混同しないこと。
import { BrowserModule } from "@angular/platform-browser";import { NgModule } from "@angular/core";import { AppComponent } from "./app.component";@NgModule({declarations: [AppComponent],imports: [BrowserModule],providers: [],bootstrap: [AppComponent]})export class AppModule {}
ルートモジュールは1つはAngularのアプリケーションにおいて必ず1つは必要になる。
小規模アプリの開発ではルートモジュールだけで足りるが
大規模開発になると
などを作る場合もある
各モジュールの役割は下記になる
エントリーポイント(src/main.ts)により呼び出されるモジュールであり
自動生成されるapp.module.tsのこと
urlのルーティングでコンポーネント表示を管理するモジュール
app-routing.module.tsのこと
機能やサブシステムごとに作成されるモジュール
共通のコンポーネント等を管理する
特にルートモジュール(app.module.ts)に実装する内容はかなり重要なので
こまかくまとめておく
自動生成されたapp.module.tsは下記のようになっている
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';@NgModule({declarations: [AppComponent,],imports: [BrowserModule,AppRoutingModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
@NgModuleを付けることでangularのモジュール(ngModule)として定義できる。
@NgModuleには下記のオブジェクトを渡す必要がある
@NgModule({declarations: 配列,imports: 配列,exports: 配列,providers: 配列,bootstrap: [AppComponent]})
bootstrapプロパティはルートモジュールで使い、通常デフォルトのままにしておく またこの他にも
があり、適宜追加して使用する。
プロジェクト作成時に自動生成された時点でデフォルトで設定されている項目については
基本的に削除せず、追加していく形になる。
このngModule内で使用する
を追加する。
新しいコンポーネント等を作成したら、importして
declarationsに追加することが必要になる。
試しにHelloComponentを作ってみる
作成したプロジェクトに移動して下記を実行すると
コンポーネントを作ることができる
ng generate component hello
「hello works!」を表示するだけのコンポーネント
<p>hello works!</p>
hello.componentのtsファイル。
今回はサンプルのため特に処理は実装しない。
import { Component, OnInit } from '@angular/core';@Component({selector: 'app-hello',templateUrl: './hello.component.html',styleUrls: ['./hello.component.css']})export class HelloComponent implements OnInit {constructor() { }ngOnInit(): void {}}
プロジェクト生成時に自動生成されるapp.component.htmlを
下記のように編集する
<app-hello></app-hello>
作成したhello.componentをapp.module.tsに追加する。
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HelloComponent } from './hello/hello.component';@NgModule({declarations: [AppComponent,HelloComponent],imports: [BrowserModule,AppRoutingModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
ng serveで実行すると
作成したhello.componentが表示される。
AppComponent内でHelloComponentを使用している。
実際にcodesandboxでサンプルを作って動作を確認する
他のngModuleをこのngModuleで利用できるようにする。
angularモジュールを使うにも使用する。
※パッケージなどの場合はnpmでインストールしておく必要あり。
import { NewComponent } from "./component/new.component";import { NewDirective } from "./common/new.directive";// angularのライブラリをimportimport { FormsModule, ReactiveFormsModule } from '@angular/forms'@NgModule({// 設定declarations: [NewComponent,NewDirective],imports: [FormsModule,ReactiveFormsModule],exports: 配列,providers: 配列,bootstrap: [AppComponent]})
このngModuleのコンポーネントやディレクディブなとを
他のモジュールでも使用可能にする。
他のモジュールと共有用モジュールを作成するときなどに使用する
import { exportComponent } from "./component/export.component";import { CommonModule } from '@angular/common';@NgModule({declarations: [exportComponent],imports: [CommonModule],exports: [exportComponent],providers: 配列,})export class SharedModule {}
exportsされたngModuleをimportsして使う
import { NewComponent } from "./component/new.component";import { NewDirective } from "./common/new.directive";import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { SharedModule } from './shared/shared.module';@NgModule({// 設定declarations: [NewComponent,NewDirective],imports: [FormsModule,ReactiveFormsModule,SharedModule],exports: 配列,providers: 配列,bootstrap: [AppComponent]})export class AppModule {}
importsとexportsの使い方については下記の記事で詳しく
まとめています!
サービスクラスを使うときに、ここでDIすることができる。 サービスクラスをDIするのはここでなくてもできるため必須ではない。
import { NewComponent } from "./component/new.component";import { NewDirective } from "./common/new.directive";import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { SharedModule } from './shared/shared.module';import { AdditionInfoService } from './service/AdditionInfoService';@NgModule({// 設定declarations: [NewComponent,NewDirective],imports: [FormsModule,ReactiveFormsModule,SharedModule],exports: [],providers: [AdditionInfoService],bootstrap: [AppComponent]})export class AppModule {}
コンポーネントをルーティングのパスに応じて表示する。
ルーティングモジュールを作成して
ルートモジュールでimportsすることでコンポーネントをルーティングで
表示できるようにする
パスとコンポーネントの紐づけを設定する
import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';// コンポーネントをimportimport { HelloComponent } from '../app/hello/hello.component';const routes: Routes = [{path: 'HelloComponent',component: HelloComponent,//ルーティングを設定// canDeactivate: [NavigationGuard],},];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule],})export class AppRoutingModule {}
ルートモジュールでapp-routing.module.tsをimportsし、設定する
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HelloComponent } from './hello/hello.component';@NgModule({declarations: [AppComponent, HelloComponent],imports: [BrowserModule, AppRoutingModule],providers: [],bootstrap: [AppComponent],})export class AppModule {}
app.component.htmlを編集し、ルーティングに応じたコンポーネントを
表示できるようにする
router-outletに、パスに応じたコンポーネントが組み込まれる
<h1>Angular</h1><div><a routerLink="HelloComponent">Hello</a></div><div><a routerLink="/">戻る</a></div><router-outlet></router-outlet>
codesandboxで実際に動かしてみると下記のようになる。
リンククリックで< router-outlet >の部分がhellocomponentに置き換わっていることがわかる。
現状は使えているが、長い間触らないと忘れてしまうので
angularの基本的な仕組みについて簡単にまとめてみた。