ラベル TypeScript の投稿を表示しています。 すべての投稿を表示
ラベル TypeScript の投稿を表示しています。 すべての投稿を表示

2019年4月7日日曜日

Angular in-memory-web-api を使う


Angular が提供している in memory web api の使い方を紹介します。
アプリケーションを開発する際に、サーバー側で REST API を用意するほどではないモックアップ作成時に便利な簡易 REST API です。

angular/in-memory-web-api
https://github.com/angular/in-memory-web-api


パッケージのインストール

npm i angular-in-memory-web-api



InMemoryDbService 実装クラスの用意

InMemoryDbService 実装クラスで、createDb() メソッド内にデータを実装しておきます。

product.service.ts

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class ProductService implements InMemoryDbService {
  createDb() {
    const products = [
      { id: 1, name: 'orange juice' },
      { id: 2, name: 'green tea' },
      { id: 3, name: 'oolong tea' },
      { id: 4, name: 'tomato juice' }
    ];
    return { products };
  }
}


HttpClientInMemoryWebApiModule のインポート

InMemoryDbService 実装クラスをモジュールに登録します。

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';

import { AppComponent } from './app.component';

import { ProductService } from './product.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpClientInMemoryWebApiModule.forRoot(ProductService)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }



API の呼び出し

in-memory-web-api への通信は、HttpClient モジュールを通じて行うことができます。(HttpClient の通信を捕まえて、createDb() メソッドに実装しているインメモリデータを返します。)

app.component.ts
import { ProductService } from './product.service';
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private http: HttpClient) { }

  title = 'InMemoryDbService';

  async getProducts() {
    const res = await this.http.get('/api/products/').toPromise();
    console.log(res);
  }
}

app.component.html
<button (click)="getProducts()">get products</button>



Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年3月9日土曜日

Angular モジュールの lazy loading (遅延読み込み)

Angular ではルーティング時に呼び出すモジュールを、アプリケーション起動時ではなく、初回ルーティング時に読み込む仕組み(lazy loading, 遅延読み込み)が提供されています。

今回は lazy loading の設定方法を紹介します。

アプリケーション作成

まずはアプリケーションを作成します。Angular CLI を利用すると、ルーティング機能を追加するか聞かれるので、y(es) とします。

ng new routing-test
? Would you like to add Angular routing? (y/N) y
そうすると、ルーティング機能が追加されたアプリケーションが出来上がります。app-routing.module.ts があること、app.module.ts に AppRoutingModule がインポートされていることを確認することができます。

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


モジュールとコンポーネントの追加

次に、ルーティング対象のモジュールと、そのモジュール配下にコンポーネントを作成します。

ng g m dashboard --routing
ng g c dashboard/list

dashboard.module.ts に ListComponent が登録されていることを確認します。


ルーティングモジュールの編集

app-routing.module.ts の routes プロパティに、次のルーティング情報を指定します。dashboard という URL (path)が呼ばれたときに、dashboard フォルダ配下の dashboard.module.ts ファイルの DashboardModule クラスを呼び出す、という指定を行っています。loadChildren に DashboardModule の参照を指定することで、lazy loading (遅延読み込み)とすることができます。

app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: './dashboard/dashboard.module#DashboardModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


続いて、Dashboard モジュールの表示コンポーネントの指定をします。「アプリケーションルート/dashboard」が呼び出された時に ListComponent を表示するよう指定を行っています。

dashboard-routing.module.ts
import { ListComponent } from './list/list.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    component: ListComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule { }

routerLink の設定

appcomponent.html に、dashboard へのリンクを追加します。dashboard のリンクをクリックすると、<router-outlet> タグに、dashboard モジュールの list コンポーネントが表示されます。

app.component.html
<p>ルーティングテスト</p>
<a routerLink="">top</a>
<br>
<a routerLink="/dashboard">dashboard</a>

<router-outlet></router-outlet>

アプリケーションの実行と、lazy loading の確認

dashboard にアクセスすると、dashboard モジュールが初めて読み込まれることを確認することができます。



以上、Angular の lazy loading (遅延読み込み)の紹介でした。

Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月10日日曜日

Angular @ViewChild デコレーター

Angular では、HTML テンプレート上に定義されているコンポーネントを TypeScript 側から参照する機能として、@ViewChild デコレーターが提供されています。

例えば、AppComponent に次の MyLabelComponent を利用しているとします。


MyLabelComponent (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabelComponent (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

AppComponent の TypeScript 上で、@ViewChild デコレーターに型を指定するかたちで、MyLabelComponent を参照することができます。

AppComponent (TypeScript)
import { Component, ViewChild } from '@angular/core';
import { MyLabelComponent } from './my-label/my-label.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app1';

  @ViewChild(MyLabelComponent) myLabel: MyLabelComponent;

  getText() {
    console.log(this.myLabel.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label text="abc"></app-my-label>


なお、複数の MyLabelComponent が存在する場合、 テンプレート参照変数を利用してコンポーネントを特定します。(この例では、HTML テンプレート上の #label1 や #label2 がテンプレート参照変数です。)

 AppComponent (TypeScript)
export class AppComponent {
  title = 'app1';

  @ViewChild('label1') myLabel1: MyLabelComponent;
  @ViewChild('label2') myLabel2: MyLabelComponent;

  getText() {
    console.log(this.myLabel1.text);
    console.log(this.myLabel2.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label #label1 text="abc"></app-my-label>
<app-my-label #label2 text="def"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

Angular @Input デコレーター

Angular の @Input デコレーターは、親コンポーネントから子コンポーネントに対してデータを渡す際に使います。

例えば、子コンポーネントとして MyLabel コンポーネントがあるとします。

MyLabel コンポーネント (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabel コンポーネント (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

 コンポーネントに text プロパティを定義し、更に @Input デコレーターを付与しています。外部コンポーネントからは、@Input デコレーターの引数に指定している 'text' というプロパティを利用して値を渡すことができるようになります。※ 引数を省略すると、変数名(ここでは 'text')というプロパティ名になります。

親コンポーネントからは次のように利用しています。 text というプロパティ(インプット)に対して "abc" という文字列を指定しています。

App コンポーネント(HTML テンプレート)
<app-my-label text="abc"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2018年11月11日日曜日

Angular ngModel 使い方

Angular の ngModel の使い方をメモしておきます。黄色でハイライトされている部分を追加すると ngModel を利用できるようになります。

1.app.module.ts

ngModel は angular/forms の FormsModule に含まれているので、FormsModule をインポートします。また、NgModel デコレータの imports で FormsModule をインポートします。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';//追加

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//追加
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.app.component.html

HTML テンプレートで ngModel に変数 name をバインドします。
<input type="text" [(ngModel)]="name">
{{name}}

3.app.component.ts

変数 name の初期値を設定します。
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  name = 'sasaki';//追加
}

Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2018年7月28日土曜日

Angular - ngIf ディレクティブ

Angular の ngIf ディレクティブの利用例です。

HTML テンプレート
<p>
  <input type="button" value="toggle flag" (click)="toggleFlag()">
</p>

<div #ifBlock *ngIf="flag; else elseBlock">
  This is ifBlock
</div>

<ng-template #elseBlock>
  Here is elseBlock.
</ng-template>

TypeScript
export class IfComponent implements OnInit {

  flag: boolean;


  constructor() { }

  ngOnInit() {
    this.flag = true;
  }


  toggleFlag(){
    this.flag = !this.flag;
  }
}
TypeScript の flag 変数の値に応じて表示します。flag 変数の値が true のときは #ifBlock のある div タグが、false のときは #elseBlock のある ng-template の中が表示されます。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2018年2月4日日曜日

Angular5 TODO リスト作成

Angular5 で簡易な TODO リストを作成する実装例を紹介します。

環境準備

node.js 及び npm のインストール

Angular によるアプリケーション開発を行うにあたり、これら機能を利用しますので、それぞれインストールします。インストール後、バージョンを確認します。

バージョン確認
node -v
npm -v

Angular インストール

次のコマンドで Angular CLI をインストールします。
npm install @angular/cli -g


Angular バージョ確認
ng -v


Angular CLI プロジェクトの作成、及びアプリケーションの起動

次のコマンドで Angular CLI プロジェクトを作成します。
ng new todoApp

作成したアプリケーションフォルダに移動
cd todoApp

アプリケーション起動
ng serve -o

→ ブラウザが起動してアプリケーションを表示


ここまでで開発の準備になります。ここから Angular CLI プロジェクトに実装を加えていきます。

機能実装

機能の実装は 1 ~ 15 のステップになります。

タスク数の表示

1.変数 taskText, taskCount を宣言する。

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';

  //1
  taskText:string;
  taskCount: number;
}


2.インターポレーションでテンプレートに taskCount を表示する。

app.component.html
<div style="text-align:center">
  <h1>
      タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>
</div>


3.FormsModule をインポートする。

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//3

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//3
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
}


タスクの追加機能

コンポーネントが初期化されるタイミングで発生するライフサイクルイベントをハンドルし、コンポーネントで利用する変数の初期化を行います。

4. OnInit をインポートする。
5. AppComponent に OnInit を実装する。
6. 変数 tasks を宣言する。
7. ngOnInit イベント内で taskText を空文字で、taskCount の値を tasks の要素数で初期化する。
8. addTask メソッドを追加する。

app.component.ts
import { Component, OnInit/*4*/ } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit/*5*/ {
  title = 'app';

  //1
  taskCount: number;
  tasks = [];//6
  
  ngOnInit(){
    //7
    this.taskText = "";
    this.taskCount = this.tasks.length;
  }

  //8
  addTask(taskNameValue: string){
    this.tasks.push(taskNameValue);
    this.taskCount = this.tasks.length;
  }
}

続いてテンプレート(HTML)側にも、データのバインドなどを実装していきます。


9. input(text) を実装し、taskName という名前をつける。
10. input(text) の value に ngModel を利用して taskText の値を双方向バインドする。
11. input(button) に click イベントを実装する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

ここまでで、input(button) をクリックすると、コンポーネント側で tasks 配列の要素が追加され、テンプレート側でバインドしている taskCount の値も増えていくことを確認することができます。

タスクのリスト表示

続けて、追加したタスクをリスト形式で表示するための実装を加えていきます。


12. tasks 配列の各要素をリスト表示する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks">
    {{ task }}
  </li>
</ul>


13. タスクリストの位置調整

app.component.css
ul {
    position: relative;
    left: 40%;
}

ここまでで、ボタンクリックでタスクが追加していくようになります。

タスクの削除

タスクの追加ができたら、タスクの削除もできるようにします。タスクの削除は、タスク(li 要素)をクリックした時に行います。

14. input(button) に click イベントを登録する。

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks; let idx = index;" (click)="removeTask(idx)"><!-- 14 -->
    {{ task }}
  </li>
</ul>

コンポーネント側で、タスクを削除するための removeTask イベントハンドラを実装します。

15. app.component.ts
//15
removeTask(idx:number){
  this.tasks.splice(idx, 1);
}

以上で、簡単ではありますが、Angular を利用した TO DO リストの作成ができました。


全ソースコード

各ファイルのソースコードは次のようになっています。

app.component.ts
import { Component, OnInit/*4*/ } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit/*5*/ {
  title = 'app';

  //1
  taskText:string;
  taskCount: number;

  tasks = [];//6
  
  ngOnInit(){
    //7
    this.taskText = "";
    this.taskCount = this.tasks.length;
  }

  //8
  addTask(taskNameValue: string){
    this.tasks.push(taskNameValue);
    this.taskCount = this.tasks.length;
    this.taskText = "";
  }
  //15
  removeTask(idx:number){
    this.tasks.splice(idx, 1);
  }
}

app.component.html
<div style="text-align:center">
  <h1>
    タスク数 = {{ taskCount }}<!-- 2 -->
  </h1>

  <input #taskName type="text" [(ngModel)]="taskText"><!-- 9, 10 -->

  <input type="button" value="タスク追加" (click)="addTask(taskName.value)"><!-- 11 -->
</div>

<ul>
  <!-- 12 -->
  <li *ngFor="let task of tasks; let idx = index;" (click)="removeTask(idx)"><!-- 14 -->
    {{ task }}
  </li>
</ul>

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';//3

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//3
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.css
ul {
    position: relative;
    left: 40%;
}
以上になります。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html