Angular2でユーザー定義の構造ディレクティブを作成する方法を確認しました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
※目次をクリックすると目次の下部にコンテンツが表示されます。
・最も一般的なディレクティブで、テンプレートと共に定義。
②構造ディレクティブ(Structural directives)
・DOM用要素を追加、除去する事によってDOMのレイアウトを変更する。
・NgFor、NgIf、NgSwitchのビルトインディレクティブが代表的。
③属性ディレクティブ(Attribute directives)
・要素の外観や振る舞いを変更するディレクティブ。
・NgStyleビルトインディレクティブは、いくつかの要素スタイルを同時に変更できる。
・@Directiveデコレーターでは、そのディレクティブに結びつく属性を識別するセレクタを指定する。
・コントローラクラスでそのディレクティブの振る舞いを実装する。
・コンストラクタで、TemplateRefとViewContainerRefを指定し、インジェクトする。
@Directive({
selector: '[myUnless]'
})
export class UnlessDirective {
constructor(
private _templateRef: TemplateRef,
private _viewContainer: ViewContainerRef
) { }
@Input() set myUnless(condition: boolean) {
if (!condition) {
this._viewContainer.createEmbeddedView(this._templateRef);
} else {
this._viewContainer.clear();
}
}
}
@Component({
selector: 'my-app',
template: `
<button (click)="condition = !condition">
Set 'condition' to {{condition ? 'False': 'True'}}
</button>
<p *myUnless="condition">
"condition"がfalseの場合に表示
</p>
<p *myUnless="!condition">
"condition"がtrueの場合に表示
</p>
`,
directives: [UnlessDirective]
})
export class MyApp {
condition = true;
}
bootstrap(MyApp);
●ViewContainerRef
・ディレクティブは、ViewContainerRefを使って実行時にビューをインスタンス化、挿入、移動、破棄する。
・ViewContainerRefは、<template>要素の結果として生成され、このアクションが実行されるカレントビューの位置を表す。
・ビューは、ViewMetadataの子、<template>要素の兄弟として生成される。したがって、子ビュー内のディレクティブはそれを生成したディレクティブをインジェクトすることができない。
・テンプレート上の組み込みビューをインスタンス化するには、ViewContainerRefを使用する。これは、ビューを生成し、ビューコンテナーに付与する。
○createEmbeddedView()
・構文
createEmbeddedView(templateRef: TemplateRef, index?: number) : EmbeddedViewRef
・templateRefに基づく組み込みビューをインスタンス化し、コンテナー内の指定した位置に挿入する。
indexが未指定の場合は、新しいビューはコンテナー内の最後に挿入される。
○clear()
・コンテナー内のすべてのビューを破棄する。
●TemplateRef
・組み込みビューをインスタンス化するのに使用される組み込みテンプレートを表す。
・<template>要素または”*”でプレフィックスされたディレクティブに配置されたディレクティブを介してTemplateRefにアクセスできる。
<template>要素は以下のように短縮形式で記述することができる。
<ul>
<template [foo]="bar">
<li title="text"></li>
</template>
</ul>
<ul>
<li *foo="bar" title="text"></li>
</ul>
Bootstrap : 3.x
<html>
<head>
<title>Angular 2 Demo</title>
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
<script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="./js/systemjs.config.js"></script>
<script>
System.import('./ts/app.ts').catch(function(err){ console.error(err); }); </script>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="container">
<my-app>Loading...</my-app>
</div>
</body>
</html>
(systemjs.config.js)
(function (global) {
var ngVer = '@4.4.3';
System.config({
transpiler: 'ts',
typescriptOptions: {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"strict": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
'npm:': 'https://unpkg.com/'
},
map: {
'app': 'app',
'@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.0.1',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.3.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component, Directive, Input } from '@angular/core';
import { TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[myUnless]'
})
export class UnlessDirective {
constructor(
private _templateRef: TemplateRef,
private _viewContainer: ViewContainerRef
) { }
@Input() set myUnless(condition: boolean) {
if (!condition) {
this._viewContainer.createEmbeddedView(this._templateRef);
} else {
this._viewContainer.clear();
}
}
}
@Component({
selector: 'my-app',
template: `
<button (click)="condition = !condition">
Set 'condition' to {{condition ? 'False': 'True'}}
</button>
<p *myUnless="condition">
"condition"がfalseの場合に表示
</p>
<p *myUnless="!condition">
"condition"がtrueの場合に表示
</p>
`,
directives: [UnlessDirective]
})
export class AppComponent {
condition = true;
}
@NgModule({
imports: [
BrowserModule
],
declarations: [
AppComponent,
UnlessDirective
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
-
基本、仕組み
- Angular2のモジュール、コンポーネント、bootstrapの概要
- データバインディングの概要
- プロパティバインディングとアトリビュートバインディング
- イベント処理
- NgClass、NgStyle、クラスバインディング、スタイルバインディングを使ってcss設定
- 内挿(interpolation)、2Wayバインディングの概要
- NgForを使ってリストやテーブルを作成
- NgSwitchで内部にあるHTMLテンプレートの表示を切り替え
- NgIf、[style.display]、[hidden]を使って表示、非表示を切り替え
- inputs、@Inputを使ってディレクティブ間で値を受け渡し
- outputs、@Output、EventEmitterを使ってカスタムイベントを定義
- カスタム構造ディレクティブ作成
- NgForを使ってラジオボタン、selectメニューを作成
- フォームのバリデーションチェック、動的にCSS追加
- カスタムバリデート、カスタムフォーム
- フォームで非同期のバリデート、入力値の変更検知
- サービスの概要、サービスを使ったサンプル作成
- Promiseを使って非同期にデータを取得
- ビルトインパイプ
- カスタムパイプでソート(orderBy)機能のサンプル作成
- Bootstrap3を使ってページング
- ステートフル、非同期パイプの使用方法
- HTTPでサーバーからJSONデータ取得
- HTTP POST送信
- Observableを使ってHTTPリクエストを複数送信
- JSONPを使ってサーバー通信
- ルーティング設定、RESTのサンプル作成
- Angular2でNavigationEndイベントを使ってflashメッセージ表示
- ルーターの遅延ロード(AsyncRoute)とrouterCanDeactivateの使用方法
- Angular v4のUpgradeModuleを使ってAngularJS v1アプリを動作
- Angular v4のUpgradeModuleを使ってAngularJS v1アプリとのハイブリッドアプリを動作
ディレクティブ
フォーム
サービス
パイプ
HTTP
ルーティング
UpgradeModuleを使ってv1アプリを動作、ハイブリッで動作
-
基本、仕組み
- Angular2のモジュール、コンポーネント、bootstrapの概要
- データバインディングの概要
- プロパティバインディングとアトリビュートバインディング
- イベント処理
- NgClass、NgStyle、クラスバインディング、スタイルバインディングを使ってcss設定
- 内挿(interpolation)、2Wayバインディングの概要
- NgForを使ってリストやテーブルを作成
- NgSwitchで内部にあるHTMLテンプレートの表示を切り替え
- NgIf、[style.display]、[hidden]を使って表示、非表示を切り替え
- inputs、@Inputを使ってディレクティブ間で値を受け渡し
- outputs、@Output、EventEmitterを使ってカスタムイベントを定義
- カスタム構造ディレクティブ作成
- NgForを使ってラジオボタン、selectメニューを作成
- フォームのバリデーションチェック、動的にCSS追加
- カスタムバリデート、カスタムフォーム
- フォームで非同期のバリデート、入力値の変更検知
- サービスの概要、サービスを使ったサンプル作成
- Promiseを使って非同期にデータを取得
- ビルトインパイプ
- カスタムパイプでソート(orderBy)機能のサンプル作成
- Bootstrap3を使ってページング
- ステートフル、非同期パイプの使用方法
- HTTPでサーバーからJSONデータ取得
- HTTP POST送信
- Observableを使ってHTTPリクエストを複数送信
- JSONPを使ってサーバー通信
- ルーティング設定、RESTのサンプル作成
- Angular2でNavigationEndイベントを使ってflashメッセージ表示
- ルーターの遅延ロード(AsyncRoute)とrouterCanDeactivateの使用方法
- Angular2とBootstrap4でAccordion
- Angular2とBootstrap4でCarousel
- Angular2とBootstrap4でドロップダウン
- Angular2とBootstrap4でツールチップ、ポップオーバー
- Angular2とBootstrap4でタブ
- Angular2とBootstrap4でページネーション(ページャー)
ディレクティブ
フォーム
サービス
パイプ
HTTP
ルーティング
Bootstrapと連携