wheatandcatの開発ブログ

React Nativeで開発しているペペロミア & memoirの技術系記事を投稿してます

@angular/formsについて

noteに投稿を始めました。今回はその過程で一番最後に開発したangularの話について

note.mu

@angular/formsとは

angularでフォーム入力をバインドする時に使うモジュールです。

angularドキュメントが非常に充実しているので、詳しくは下のリンク参照

Angular 日本語ドキュメンテーション

github

ここで実装しています

github.com

実装の仕方

↑のgithubのsourceに沿って紹介

入力フォームのモデル生成

f:id:wheatandcat:20180904083315p:plain

画像の入力に合わせて入力フォームのモデルを生成するために以下のコマンドを実行

ng generate class User

「src/app/user.ts」が生成されるので、中身を以下に修正

■ src/app/user.ts

export class User {

  constructor(
    public name: string,
    public genderCode: number
  ) {}

}

入力フォームのモデルをコンポーネントに追加

■ src/app/app.component.ts

import { Component, OnInit } from "@angular/core";
import { User } from "./user"; // ← 追加

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {

  model = new User("", 1); // ← 追加


(以下略)

@angular/formsをモジュールに追加

■ src/app/app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";   // ←追加
import { HttpClientModule } from "@angular/common/http";
import { FormsModule } from "@angular/forms";

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

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

htmlにバインドを追加

上記で追加した @angular/forms を使って入力フォームのモデルにバインドしていく

テキスト入力のバインド

テキスト入力とmodel.nameをバインドさせる

■ src/app/app.component.html

    名前:
    <input name="name" placeholder="name" [(ngModel)]="model.name" />

ラジオボタン入力のバインド

テキスト入力とmodel.genderCodeをバインドさせる

■ src/app/app.component.html

    性別:
    <input type="radio" id="male" name="genderCode" [value]="1" [(ngModel)]="model.genderCode" [checked]="model.genderCode === 1" />
    <label for="male" style="padding-right:8px">男性</label>
    <input type="radio" id="female" name="genderCode" [value]="2" [(ngModel)]="model.genderCode" [checked]="model.genderCode === 2" />
    <label for="female">女性</label>

(最後)バインドしたモデルを参照する

入力したモデルの値を参照する

■ src/app/app.component.ts

import { Component, OnInit } from "@angular/core";
import { User } from "./user";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {

  model = new User("", 1); 

  onClick() {  // ← 追加
    console.log(this.model)
  }

追加した値参照用のメソッドを呼ぶ

■ src/app/app.component.html

<button (click)="onClick()">ログ確認</button>

ここまでバインド & 参照完了