Formlyは、フォームの作成と操作を支援するAngularJSの人気のあるライブラリです。 これで、 @ngx-formlyを使用してFormlyinAngular2+を楽しむこともできます。 単純なJSONオブジェクトを使用してほぼすべての種類のリアクティブフォームを簡単に定義できるモジュールを提供します。

Angularのフォームを初めて使用する場合は、リアクティブフォームの概要についてこちらをお読みください。

Formlyの使い方を簡単に見てみましょう。

設定

Formlyは、 AngularMaterialまたはBootstrapで使用できます。ここでは、AngularMaterialと一緒に使用します。

まず、npmまたはYarnを使用して必要なパッケージをインストールしましょう。

$ npm install @ngx-formly/core @ngx-formly/material

# or, using Yarn:
$ yarn add @ngx-formly/core @ngx-formly/material

次に、必要なコンポーネントモジュールを使用して、マテリアル用に別のモジュールをセットアップします。

Material.module.ts
import { NgModule } from '@angular/core';

import {
  MatButtonModule,
  MatInputModule,
  MatFormFieldModule,
  MatCheckboxModule,
  MatSelectModule
} from '@angular/material';

そして最後に、アプリモジュールで、カスタムマテリアルモジュールとFormlyに必要なモジュールをインポートしましょう。

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { MaterialModule } from './material.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyMaterialModule } from '@ngx-formly/material';
import { AppComponent } from './app.component';

最後に、カスタムマテリアルテーマを使用している場合を除き、事前に作成されたテーマの1つをグローバルスタイルファイルにインポートしてください。

styles.css
@import '~https://fonts.googleapis.com/icon?family=Material+Icons';
@import '~@angular/material/prebuilt-themes/indigo-pink.css';

使用法

すべての適切なモジュールがアプリモジュールにインポートされたので、Formlyとそのformly-formコンポーネントの使用を開始する準備が整いました。

2つの単純なオブジェクトを使用して、コンポーネントの1つでフォームを定義できます。各フォームフィールドのキーを持つモデルと、FormlyFieldConfigタイプのオブジェクトの配列を持つオブジェクトです。モデル。

フォームの設定方法を説明するために、簡単なサーカス衣装注文フォームを作成しましょう。

app.module.ts
import { Component } from '@angular/core';

import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
@Component({ ... })
export class AppComponent {
  orderForm = new FormGroup({});
  // our model:
  order = {
    tagName: '',
    color: 'powder-blue', // will default to this value
    quantity: 1,
    size: 'M',
    terms: false
  };
  // our field configuration. Keys should match our model:
  orderFields: FormlyFieldConfig[] = [
    {
      key: 'tagName',
      type: 'input', // input type
      templateOptions: {
        type: 'text',
        label: 'Tag name for your outfit',
        placeholder: 'tag name'
      },
      validation: {
        messages: {
          maxLength: 'Tag name is too long'
        }
      },
      validators: {
        // limit to 25 characters
        maxLength: ({ value }) => {
          return value.length <= 25;
        }
      }
    },
    {
      key: 'color',
      type: 'select',
      templateOptions: {
        label: 'Outfit color',
        options: [
          { label: 'Powder blue', value: 'powder-blue' },
          { label: 'Orange crush', value: 'orange-crush' },
          { label: 'Purple haze', value: 'purple-haze' }
        ]
      }
    },
    {
      key: 'quantity',
      type: 'input',
      templateOptions: {
        type: 'number',
        label: 'How many outfits?',
        placeholder: 'quantity',
        required: true
      }
    },
    {
      key: 'size',
      type: 'select',
      defaultValue: 'M',
      templateOptions: {
        label: 'Size',
        options: [
          { label: 'Small', value: 'S' },
          { label: 'Medium', value: 'M' },
          { label: 'Large', value: 'L' }
        ]
      }
    },
    {
      key: 'terms',
      type: 'checkbox',
      templateOptions: {
        label: 'You accept our terms and conditions',
        required: true
      }
    }
  ];

構成はすぐにかなり長くなる可能性がありますが、すべてが非常にシンプルで宣言型のままです。 上記の例は、いくつかの非常に便利なことを行う方法を示しています。

  • デフォルト値の定義。
  • カスタム検証と検証エラーマッサージ。
  • 必要に応じてフィールドにマークを付けます。
  • selectフィールドの場合のフィールドタイプとオプションの指定。

そして最後に、コンポーネントテンプレートのフォームのマークアップをこれ以上簡単にすることはできません。 formly-form コンポーネントの周りにリアクティブフォームをラップするだけで、modelおよびfieldsconfigurationオブジェクトの入力が追加されます。

app.component.html
<form [formGroup]="orderForm" (ngSubmit)="onSubmit(order)">
  <formly-form [model]="order" [fields]="orderFields">
    <button mat-raised-button color="primary" type="submit">
      Submit
    </button>
  </formly-form>
</form>

formly-form コンポーネントは、コンポーネントの初期化時に、構成されたすべてのフォームフィールドを動的に作成します。 フォームの例は次のようになります。

🎪これで私たちの小さなイントロは終わりです! Formlyを使用して実行できるその他の例については、公式ウェブサイトをご覧ください。