クリックして子コンポーネントを追加する|AngularでWebサイト作成
Angularの学習の為に、AngularでWebサイトを作ってみることにしました(Angularのバージョンは4.3.6です)。
適宜作業内容をまとめていきます。
基本的な部分は公式チュートリアルなどを参考にしながら進めています。
今回は「+」ボタンをクリックして登録フォームを追加するコンポーネントを作成してみます。
開発環境
・OS:Windows8.1 64bit
・node:v7.2.1
・npm:4.0.5
・Angular:4.3.6
・開発ツール:VisualStudioCode
Angularサンプルプログラム
子コンポーネントのテンプレート
まずは追加する子コンポーネントのテンプレートを作成しておきます。
sub.component.html
1 2 3 4 5 | < li style = "list-style:none;margin:10px;" > < input class = "form-control" placeholder = "name" > < input class = "form-control" placeholder = "age" > < button class = "btn btn-default" (click)="removeObject()">削除</ button > </ li > |
2つのテキストフォームを表示するコンポーネントです。
次に、親コンポーネントのテンプレートを作成します。
parent.component.html
1 2 3 4 | < form class = "form-inline" > < div #add></ div > < button class = "btn btn-warning" style = "margin-left:10px;" (click)="addComponent()">+</ button > </ form > |
「+」をクリックするとaddComponentメソッドが実行されるようにします。
parent.component.ts(該当箇所のみ抜粋しています)
1 2 3 4 5 6 7 8 9 10 11 | export class ParentComponent implements OnInit { @ViewChild( 'add' , { read: ViewContainerRef }) container: ViewContainerRef; constructor( private _cfr: ComponentFactoryResolver ){} addComponent(){ var sub = this ._cfr.resolveComponentFactory(SubComponent); var subComponent = this .container.createComponent(sub); subComponent.instance._ref = subComponent; } } |
まとめ
いくつかの要素を追加したときに全体をPostし保存するなど、もう少し作りこまなければならない部分がありますが、
これでひとまずクライアント側で要素追加を行うことができるようになりました。
WEBアプリケーション関連 人気連載リンク
基礎からPHPWEBアプリ解発を学ぶなら・・
PHP基礎 連載
より実践的なWEBアプリ開発講座!Bootstrap活用を学ぶなら・・
魁!小野の塾 連載