Carpe Diem

備忘録

Angular2でのForm 〜Model Driven編〜

概要

前回はTemaplate Drivenなフォームの作り方を紹介しました。
今回はModel Drivenなフォームの作り方を紹介します。

環境

  • angular-cli 1.0.0-beta.25.5
  • Angular 2.4.3

完成形

成果物はこちら

github.com

書き方

model.component.html

<form [formGroup]="f">
  <label>Firstname:</label>
  <input type="text" formControlName="first">

  <label>Lastname:</label>
  <input type="text" formControlName="last">

  <button type="submit" (click)="loginForm()">Submit</button>
  <div>
    <span>{{ f.value | json }}</span>
  </div>
</form>

ポイント

  • formGroupにModelから変数fをセット
  • inputにformControlNameを設定します。設定する名前は変数fのフィールド名

model.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-model',
  templateUrl: './model.component.html',
  styleUrls: ['./model.component.css']
})
export class ModelComponent implements OnInit {
  public f: FormGroup;
  private body: any;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.f = this.fb.group({
      'first':['', Validators.required],
      'last':['', Validators.required]
    });

    this.f.valueChanges
      .subscribe(value => {
        console.log(value);
        this.body = value;
      });
  }

  loginForm() {
    console.log(this.body);
  }
}

ポイント

  • FormGroupで変数を定義。
  • FormBuilderをDIできるようにします。DIするのはapp.module.tsでします。
  • FormGroupのフィールドであるvalueChangesがobservableなのでsubscribeで値を反映させる。

app.component.html

<h1>
  {{title}}
</h1>
<app-model></app-model>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

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

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

ポイント

  • ReactiveFormsModuleをimportします。この中でFormBuilderをDIしています。

動作確認

f:id:quoll00:20170122170523p:plain

入力してみます。

f:id:quoll00:20170122173715p:plain

subscribeしているので、コンソールから分かるように入力するたびにイベントが発火していることが分かります。

Template DrivenかModel Drivenか

どちらでもフォームとしての機能は満たしているので、

  • Template DrivenはAngularJSから移行する際に向いている
  • Model DrivenはObservableな書き方ができるのでRxJsと相性が良い

というくらいで考えると良いです。

ソース