NgForを使ってラジオボタン、selectメニューを生成するサンプルを作成しました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
※ラジオボタンの作成についてはこちらの記事も参照。
Angular2でイベント処理
※目次をクリックすると目次の下部にコンテンツが表示されます。
ラジオボタン
コンポーネント内にラジオボタンに表示するラベル名と値を定義し、NgForを使ってラジオボタンを生成するサンプルを作成しました。
ラジオボタンで県名を選択すると、各県の詳細情報を保持する配列データから、選択した県と同じインデックスを持つデータを選択し、リストで表示しています。
①<div *ngFor=”let item of prefs; let idx = index;”>
・NgForディレクティブで県の情報を保持する配列からデータを取得。
②<input type=”radio” [value]=”item.id” ・・・>{{item.name}}
・上記①から取得した配列データからradioボタンを表示
③(change)=”changePref(idx)”
・イベントバインディング
・ユーザーのチェック動作を”change”イベントで検知し、配列のインデックス番号を引数として”changePref”関数をコール。
④changePref(idx)関数実行
・選択したインデックス番号の詳細データ(this.select = PREFDETAILS[index])とID(this.selectedId = PREFDETAILS[index].id)を変数に割当て。
⑤[checked]=”selectedId == item.id”
・プロパティバインディング
・”selectedId変数”が対象ラジオボタンのデータのIDと等しい場合、”checked”属性をtrueにする。
ラジオボタンで県名を選択すると、各県の詳細情報を保持する配列データから、選択した県と同じインデックスを持つデータを選択し、リストで表示しています。
①<div *ngFor=”let item of prefs; let idx = index;”>
・NgForディレクティブで県の情報を保持する配列からデータを取得。
②<input type=”radio” [value]=”item.id” ・・・>{{item.name}}
・上記①から取得した配列データからradioボタンを表示
③(change)=”changePref(idx)”
・イベントバインディング
・ユーザーのチェック動作を”change”イベントで検知し、配列のインデックス番号を引数として”changePref”関数をコール。
④changePref(idx)関数実行
・選択したインデックス番号の詳細データ(this.select = PREFDETAILS[index])とID(this.selectedId = PREFDETAILS[index].id)を変数に割当て。
⑤[checked]=”selectedId == item.id”
・プロパティバインディング
・”selectedId変数”が対象ラジオボタンのデータのIDと等しい場合、”checked”属性をtrueにする。
(テンプレート)
<div *ngFor="let item of prefs; let idx = index;">
<label>
<input type="radio"
[value]="item.id"
(change)="changePref(idx)"
[checked]="selectedId == item.id">{{item.name}}
</label>
</div>
詳細データ:{{select|json}}
(コンポーネント)
changePref(index: number) {
this.select = PREFDETAILS[index];
this.selectedId = PREFDETAILS[index].id;
};
selectメニュー
Angular1ではngOptionsを使ってselectメニューを作成しましたが、Angular2ではNgForを使って記述できます。
以下のプロパティバインディングの記述は、Chromeの場合は記述しなくても選択した値がテンプレートに反映されましたが、Firefoxの場合は反映されなかったので記述してあります。
(change)=”select2=$event.target.value”
以下のプロパティバインディングの記述は、Chromeの場合は記述しなくても選択した値がテンプレートに反映されましたが、Firefoxの場合は反映されなかったので記述してあります。
(change)=”select2=$event.target.value”
<select class="form-control" required
[(ngModel)]="select2"
(change)="select2=$event.target.value" >
<option value="">都道府県を選択してください</option>
<option *ngFor="let item of prefs" [value]="item.id">{{item.name}}</option>
</select>
選択した値:{{select2}}
デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x
関連記事の目次
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 } from '@angular/core';
import { FormsModule } from '@angular/forms';
interface Pref {
id: string;
name: string;
}
interface PrefDetail {
id: string;
name: string;
kencho: string;
jinko: string;
}
@Component({
selector: 'my-app',
template:`
<strong>1)ラジオボタン</strong><br />
<div *ngFor="let item of prefs; let idx = index;">
<label>
<input type="radio"
[value]="item.id"
(change)="changePref(idx)"
[checked]="selectedId == item.id">{{item.name}}
</label>
</div>
詳細データ:{{select|json}}<br />
<strong>2)selectメニュー</strong><br />
<div class="form-group">
<select class="form-control" required
[(ngModel)]="select2"
(change)="select2=$event.target.value" >
<option value="">都道府県を選択してください</option>
<option *ngFor="let item of prefs" [value]="item.id">{{item.name}}</option>
</select>
</div>
選択した値:{{select2}}
`
})
export class AppComponent {
public prefs = PREFS;
public select = PREFDETAILS[0];
public selectedId: string = "01";
changePref(index: number) {
this.select = PREFDETAILS[index];
this.selectedId = PREFDETAILS[index].id;
};
}
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
var PREFS: Pref[] = [
{ id: "01", name: "東京都"},
{ id: "02", name: "神奈川県"}
];
var PREFDETAILS: PrefDatail[] = [
{id: "01", name: "東京都", kencho: "新宿区", jinko: "・・・・"},
{id: "02", name: "神奈川県", kencho: "横浜市", jinko: "・・・・"}
];