Angular 2 - 表單



Angular 2 還可以設計表單,這些表單可以使用 **ngModel** 指令進行雙向繫結。讓我們看看如何實現這一點。

**步驟 1** - 建立一個模型,即產品模型。建立一個名為 **products.ts** 的檔案。

Products.ts

**步驟 2** - 將以下程式碼放入檔案中。

export class Product { 
   constructor ( 
      public productid: number, 
      public productname: string 
   ) {  } 
}

這是一個簡單的類,它有兩個屬性,productid 和 productname。

**步驟 3** - 建立一個名為 product-form.component.ts 的產品表單元件,並新增以下程式碼 -

import { Component } from '@angular/core';
import { Product } from './products';

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

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

關於以上程式,需要注意以下幾點。

  • 建立 Product 類的物件,並向 productid 和 productname 新增值。

  • 使用 templateUrl 指定 product-form.component.html 的位置,該檔案將呈現元件。

**步驟 4** - 建立實際的表單。建立一個名為 product-form.component.html 的檔案,並將以下程式碼放入其中。

<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 執行應用程式。轉到您的瀏覽器,您將看到以下輸出。

Product Form
廣告