Angular2-forms

提供:Dev Guides
移動先:案内検索

Angular 2-フォーム

Angular 2は、 ngModel ディレクティブを使用して双方向バインディングを使用できるフォームを設計することもできます。 これを達成する方法を見てみましょう。

ステップ1 *-製品モデルであるモデルを作成します。 *products.ts ファイルというファイルを作成します。

Products.ts

  • ステップ2 *-ファイルに次のコードを配置します。
export class Product {
   constructor (
      public productid: number,
      public productname: string
   ) {  }
}

これは、productidとproductnameの2つのプロパティを持つ単純なクラスです。

  • ステップ3 *-product-form.component.tsコンポーネントと呼ばれる製品フォームコンポーネントを作成し、次のコードを追加します-
import { Component } from '@angular/core';
import { Product } from './products';

@Component ({
   selector: 'product-form',
   templateUrl: './product-form.componentl'
})

export class ProductFormComponent {
   model = new Product(1,'ProductA');
}

上記のプログラムについて、以下の点に注意する必要があります。

  • Productクラスのオブジェクトを作成し、productidとproductnameに値を追加します。
  • templateUrlを使用して、コンポーネントをレンダリングするproduct-form.componentlの場所を指定します。
  • ステップ4 *-実際のフォームを作成します。 product-form.componentlというファイルを作成し、次のコードを配置します。
<div class = "container">
   <h1>Product Form</h1>
   <form>
      <div class = "form-group">
         <label for = "productid">ID</label>
         <input type = "text" class = "form-control" id = "productid" required
            [(ngModel)] = "model.productid" name = "id">
      </div>

      <div class = "form-group">
         <label for = "name">Name</label>
         <input type = "text" class = "form-control" id = "name"
            [(ngModel)] = "model.productname" name = "name">
      </div>
   </form>
</div>

上記のプログラムについて、次の点に注意する必要があります。

  • ngModel ディレクティブは、製品のオブジェクトをフォーム上の個別の要素にバインドするために使用されます。
  • ステップ5 *-次のコードをapp.component.tsファイルに配置します。
import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   template: '<product-form></product-form>'
})
export class AppComponent { }
  • ステップ6 *-app.module.tsファイルに以下のコードを配置します
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { ProductFormComponent } from './product-form.component';

@NgModule ({
   imports: [ BrowserModule,FormsModule],
   declarations: [ AppComponent,ProductFormComponent],
   bootstrap: [ AppComponent ]
})
export class AppModule { }
  • ステップ7 *-すべてのコードを保存し、npmを使用してアプリケーションを実行します。 ブラウザに移動すると、次の出力が表示されます。

製品フォーム