2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angular.io Guide: Dynamic Forms

Posted at

この記事は、Angular の公式ドキュメントのDynamic Formsの章を意訳したものです。所々抜け落ち、翻訳モレがありますがあしからずご了承を。
バージョン 4.3.2 のドキュメントをベースにしています。

Dynamic Forms

フォームを手作りするには、コストがかかり時間がかかることがあります。特に多数のものが必要な場合は、お互いが似ており、変化の激しいビジネスやレギュレーションの要件に合わせて頻繁に変更が入るでしょう。

ビジネス・オブジェクト・モデルを記述するメタデータに基づいて、フォームを動的に作成した方がより経済的だと思いませんか。

このcookbookは、formGroupを使用して、異なるコントロールタイプとバリデーションを用いて簡単なフォームを動的にレンダリングする方法を示しています。それは基本的なスタートです。はるかに豊富な質問、より優雅なレンダリング、優れたユーザーエクスペリエンスをサポートするように進化するかもしれません。偉大さはすべて謙虚の始まりです。

このクックブックの例は、就職を求めるヒーローのためのオンラインアプリケーションエクスペリエンスを構築するためのダイナミックフォームです。紹介会社は、申請プロセスについて常に問題を抱えています。アプリケーションコードを変更せずにフォームを作成することができます。

ここからExampleをライブで見たり / ダウンロードすることができます。

Bootstrap

まず、AppModuleというNgModuleを作成します。

このクックブックでは、リアクティブフォームを用いて実装していきます。

ReactiveFormsReactiveFormsModuleと呼ばれる、別のNgModuleに属しているので、ReactiveFormsディレクティブにアクセスするためには、@angular/formsライブラリからReactiveFormsModuleをインポートする必要があります。

main.tsAppModuleをブートストラップします。

app.module.ts

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

import { AppComponent }                 from './app.component';
import { DynamicFormComponent }         from './dynamic-form.component';
import { DynamicFormQuestionComponent } from './dynamic-form-question.component';

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ],
  declarations: [ AppComponent, DynamicFormComponent, DynamicFormQuestionComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
  constructor() {
  }
}

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Question model

次のステップでは、フォーム機能によって必要とされるすべてのシナリオを記述できるオブジェクトモデルを定義します。ヒーローの申請プロセスには、多くの質問があるフォームが含まれています。質問はモデルの最も基本的な目的です。

次のQuestionBaseは基本的な質問クラスです。

src/app/question-base.ts

export class QuestionBase<T>{
  value: T;
  key: string;
  label: string;
  required: boolean;
  order: number;
  controlType: string;

  constructor(options: {
      value?: T,
      key?: string,
      label?: string,
      required?: boolean,
      order?: number,
      controlType?: string
    } = {}) {
    this.value = options.value;
    this.key = options.key || '';
    this.label = options.label || '';
    this.required = !!options.required;
    this.order = options.order === undefined ? 1 : options.order;
    this.controlType = options.controlType || '';
  }
}

このベースから、テキストボックスとドロップダウンの質問を表すTextboxQuestionDropdownQuestionの2つの新しいクラスを派生させることができます。考え方は、フォームが特定の質問タイプにバインドされ、適切なコントロールを動的にレンダリングすることです。

TextboxQuestionは、typeプロパティを使用してテキスト、電子メール、およびURLなどの複数のHTML5タイプをサポートしています。

src/app/question-textbox.ts

import { QuestionBase } from './question-base';

export class TextboxQuestion extends QuestionBase<string> {
  controlType = 'textbox';
  type: string;

  constructor(options: {} = {}) {
    super(options);
    this.type = options['type'] || '';
  }
}

DropdownQuestionは、選択ボックスに選択肢のリストを表示します。

src/app/question-dropdown.ts

import { QuestionBase } from './question-base';

export class DropdownQuestion extends QuestionBase<string> {
  controlType = 'dropdown';
  options: {key: string, value: string}[] = [];

  constructor(options: {} = {}) {
    super(options);
    this.options = options['options'] || [];
  }
}

次はQuestionControlServiceでは、質問をFormGroupに変換する簡単なサービスを実装します。簡単に言えば、フォームグループは質問モデルのメタデータを消費し、デフォルト値とバリデーションルールを指定することができます。

src/app/question-control.service.ts

import { Injectable }   from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { QuestionBase } from './question-base';

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: QuestionBase<any>[] ) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                              : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}

Question form components

これで、完全なモデルを定義したので、動的フォームを表すコンポーネントを作成する準備ができました。

DynamicFormComponentは、フォームのエントリーポイントとメインコンテナです。

dynamic-form.component.html

<div>
  <form (ngSubmit)="onSubmit()" [formGroup]="form">

    <div *ngFor="let question of questions" class="form-row">
      <df-question [question]="question" [form]="form"></df-question>
    </div>

    <div class="form-row">
      <button type="submit" [disabled]="!form.valid">Save</button>
    </div>
  </form>

  <div *ngIf="payLoad" class="form-row">
    <strong>Saved the following values</strong><br>{{payLoad}}
  </div>
</div>

dynamic-form.component.ts

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

import { QuestionBase }              from './question-base';
import { QuestionControlService }    from './question-control.service';

@Component({
  selector: 'dynamic-form',
  templateUrl: './dynamic-form.component.html',
  providers: [ QuestionControlService ]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: QuestionBase<any>[] = [];
  form: FormGroup;
  payLoad = '';

  constructor(private qcs: QuestionControlService) {  }

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
  }

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
}

これは質問のリストを提示し、それぞれは<df-question>コンポーネントにバインドされています。<df-question>タグは、データバインドされた質問オブジェクトの値に基づいて個々の質問の詳細をレンダリングするコンポーネントであるDynamicFormQuestionComponentと一致します。

dynamic-form-question.component.html

<div [formGroup]="form">
  <label [attr.for]="question.key">{{question.label}}</label>

  <div [ngSwitch]="question.controlType">

    <input *ngSwitchCase="'textbox'" [formControlName]="question.key"
            [id]="question.key" [type]="question.type">

    <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
      <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
    </select>

  </div> 

  <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>

dynamic-form-question.component.ts

import { Component, Input } from '@angular/core';
import { FormGroup }        from '@angular/forms';

import { QuestionBase }     from './question-base';

@Component({
  selector: 'df-question',
  templateUrl: './dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
  @Input() question: QuestionBase<any>;
  @Input() form: FormGroup;
  get isValid() { return this.form.controls[this.question.key].valid; }
}

このコンポーネントは、あなたのモデルに任意のタイプの質問を提示できます。この時点では2つのタイプの質問しかありませんが、もっと多くのことを想像することができます。ngSwitchは表示する質問のタイプを決定します。

どちらのコンポーネントでも、AngularのformGroupを使用してテンプレートHTMLを基礎となるコントロールオブジェクトに接続し、質問モデルから表示およびバリデーションルールを使用して入力します。

formControlNameformGroupは、ReactiveFormsModuleで定義されたディレクティブです。AppModuleからReactiveFormsModuleをインポートしたので、テンプレートはこれらのディレクティブに直接アクセスできます。

アンケートデータ(Questionnaire data)

DynamicFormComponent@Input()の質問にバインドされた配列の形式で質問のリストを取得します。

求人申込のために定義した一連の質問は、QuestionServiceから返されます。実際のアプリでは、これらの質問をストレージから取得します。

要点は、QuestionServiceから返されたオブジェクトを通してヒーロージョブのアプリケーションの質問を完全に制御することです。アンケートのメンテナンスは、質問配列からオブジェクトを追加、更新、および削除する簡単な作業です。

src/app/question.service.ts

import { Injectable }       from '@angular/core';

import { DropdownQuestion } from './question-dropdown';
import { QuestionBase }     from './question-base';
import { TextboxQuestion }  from './question-textbox';

@Injectable()
export class QuestionService {

  // Todo: get from a remote source of question metadata
  // Todo: make asynchronous
  getQuestions() {

    let questions: QuestionBase<any>[] = [

      new DropdownQuestion({
        key: 'brave',
        label: 'Bravery Rating',
        options: [
          {key: 'solid',  value: 'Solid'},
          {key: 'great',  value: 'Great'},
          {key: 'good',   value: 'Good'},
          {key: 'unproven', value: 'Unproven'}
        ],
        order: 3
      }),

      new TextboxQuestion({
        key: 'firstName',
        label: 'First name',
        value: 'Bombasto',
        required: true,
        order: 1
      }),

      new TextboxQuestion({
        key: 'emailAddress',
        label: 'Email',
        type: 'email',
        order: 2
      })
    ];

    return questions.sort((a, b) => a.order - b.order);
  }
}

最後に、AppComponentシェルにフォームのインスタンスを表示します。

app.component.ts

import { Component }       from '@angular/core';

import { QuestionService } from './question.service';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Job Application for Heroes</h2>
      <dynamic-form [questions]="questions"></dynamic-form>
    </div>
  `,
  providers:  [QuestionService]
})
export class AppComponent {
  questions: any[];

  constructor(service: QuestionService) {
    this.questions = service.getQuestions();
  }
}

Dynamic Template

この例ではヒーローの求人アプリケーションをモデリングしていますが、QuestionServiceから返されたオブジェクトの外にはヒーローに関する質問は何もありません。

これは、質問オブジェクトモデルと互換性がある限り、どのようなタイプの調査でもコンポーネントの用途を変えることができるため、非常に重要です。キーは、特定の質問に関するハードコードされた前提を作らずにフォームをレンダリングするために使用されるメタデータの動的データバインディングです。コントロールメタデータに加えて、動的にバリデーションを追加します。

保存ボタンは、フォームが有効な状態になるまで無効になります。フォームが有効な場合、[Save]をクリックすると、アプリケーションは現在のフォームの値をJSONとしてレンダリングします。これは、任意のユーザ入力がデータモデルにバインドされていることを証明します。データの保存と取り込みは別の機会に練習しましょう。

最終的なフォームは次のようになります。

Dynamic-Form

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?