LoginSignup
1
3

More than 5 years have passed since last update.

AngularのReactive Formsを使って入力内容に応じて動的にフォームの表示を変える

Posted at

概要

Angularで動的にフォームの入力欄を追加したり、入力内容に応じて入力欄の表示を切り替えられるか確認してみました。

前提となる参考サイト

まずはReactive Formsのドキュメントを参照。また、AngularのForm(Reactive Forms)メモのブログ記事はReactive Formsについて簡潔にまとめられていて分かりやすいです。

サンプルソース

あるテキストボックスで入力した内容に応じてもう一方のテキストの表示を切り替えるサンプルを下記に載せます。上記参考サイトの内容を少し編集したものにしています。Angular5で動作すること確認しています。

Moduleの設定

test.module.ts
import { NgModule }      from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule }  from '@angular/forms';

@NgModule({
  imports:[ CommonModule ,FormsModule , ReactiveFormsModule ]
})
export class TestModule { }

コンポーネント

test-reactiveforms.component.ts
import { Component, OnInit} from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  template: `   
    <form [formGroup]="testFormGroup">
        <div formArrayName="testlist">
           <div *ngFor="let test of testlist.controls; let i=index" [formGroupName]="i">
                City1:<input type="text" formControlName="city1" /><br/>
                <span *ngIf="test.get('city1').value == 'aaa'">
                    City2:<input type="text" formControlName="city2" />
                </span>
            </div>
         </div>
         <input type ="button"  (click)="addInput()" value="入力欄を追加" />
     </form>
  `
})
export class TestReactiveFormsComponent  { 

    // 計算式のフォームグループ
    testFormGroup: FormGroup;

    constructor(private fb: FormBuilder) {
             // フォームグループ初期化
             this.testFormGroup = this.fb.group({
                 testlist: this.fb.array([]),
             });
    }

    // 追加ボタンが押されたとき
    addInput() {
       this.testlist.push(this.fb.group({ city1: 'test1',city2: 'test2'}));
    }

    // リストの取得用
    get testlist(): FormArray {
        return this.testFormGroup.get('testlist') as FormArray;
    };

}

画面のイメージ

この状態から入力欄を追加ボタンを押します。
キャプチャ.PNG
City1の入力欄が増えます。
キャプチャ.PNG
上のCity1の入力欄に「aaa」を入力するとCity2の欄が表示されます。
キャプチャ.PNG
下のCity1の入力欄に「aaa」を入力するともう一つCity2の欄が表示されます。
キャプチャ.PNG
上のCity1の入力欄を別の値にすると、上のCity2の欄が非表示となります。
キャプチャ.PNG

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3