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
广告