Angular 2 表单

本章我们开始学习如何用组件和模板构建一个 angular 表单

我们可以使用 Angular 模板创建各种类型表单,比如 登录表单,联系人表单,商品详情表单等,而且还可以为这些表单的字段添加数据校验

现在,我们就一步步来实现表单的功能


创建项目

现在,我们就一步步来实现表单的功能

导入初始化项目

修改 angular2-forms/package.json 文件中的 "name": "angular2-typescript-quickstart" 为 "name": "angular2-forms"

然后运行

npm install --registry=https://registry.npm.taobao.org

安装依赖包

创建 Site 模型

在 angular2-forms/app 目录下新建文件 site.ts ,复制以下内容

export class Site {
  constructor(
    public id: number,
    public name: string,
    public url: string,
    public alexa?: number
  ) {  }
}

上面的代码创建了一个简单的模型类 Site,包含了三个必需字段:id,name,url,一个可选字段:alexa

标为 public 的为公有字段,alexa 后添加一个问号 (?) 表示可选字段


创建一个表单组件

每个 Angular 表单分为两部分

  1. 一个基于 html 的模板
  2. 一个基于代码的组件,用来处理数据和用户交互

在 angular2-forms/app 目录下创建文件 site-form.component.ts ,复制以下内容

import { Component } from '@angular/core';
import { Site }    from './site';

@Component({
  moduleId: module.id,
  selector: 'site-form',
  templateUrl: 'site-form.component.html'
})
export class SiteFormComponent {
  urls = ['www.fly63.com', 'www.google.com',
            'www.taobao.com', 'www.facebook.com'];
  model = new Site(1, 'Angular教程', this.urls[0], 10000);
  submitted = false;
  onSubmit() { this.submitted = true; }
  // TODO: 完成后移除
  get diagnostic() { return JSON.stringify(this.model); }
}

上面的代码首先导入了 Component 装饰器和 Site 模型

@Component 选择器 "site-form" 表示我们可以通过一个 <site-form> 标签,把此表单扔进父模板中

templateUrl 属性指向一个独立的 HTML 模板文件,名叫 site-form.component.html

diagnostic 属性用于返回这个模型的 JSON 形式

定义应用的根模块

修改 app.module.ts 来定义应用的根模块

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }  from './app.component';
import { SiteFormComponent } from './site-form.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    SiteFormComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

模块中引用了外部及声明属于本模块中的组件,比如 SiteFormComponent

因为模板驱动的表单有它们自己的模块,所以我们得把 FormsModule 添加到本应用的 imports 数组中,这样我们才能使用表单

创建根组件

修改根组件文件 app.component.ts 将 SiteFormComponent 将被放在其中

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

@Component({
  selector: 'my-app',
  template: '<site-form></site-form>'
})
export class AppComponent { }

创建一个初始 HTML 表单模板

新建文件 app/site-form.component.html ,复制以下内容

<div class="container">
    <h1>网站表单</h1>
    <form>
      <div class="form-group">
        <label for="name">网站名</label>
        <input type="text" class="form-control" id="name" required>
      </div>
      <div class="form-group">
        <label for="alterEgo">alexa 排名</label>
        <input type="text" class="form-control" id="alexa">
      </div>
      <button type="submit" class="btn btn-default">提交</button>
    </form>
</div>

required 属性设置的该字段为必需字段,如果没有设置则是可选

安装 bootstrap

在 angular2-forms 目录下输入以下命令:

npm install bootstrap --save --registry=https://registry.npm.taobao.org

修改 index.html 为以下内容,添加以下样式表

<!DOCTYPE html>
<html>
    <meta charset="UTF-8">
    <title>Angular 2 TypeScript 范例 - Angular教程(fly63.com)</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <!-- 1. 载入库 -->
    <!-- IE 需要 polyfill -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. 配置 SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. 显示应用 -->
  <body>
    <my-app>Loading...</my-app>
    <footer style="text-align: center;">
      <p></p>
      <p>Copyright © Angular教程 <a href="https://www.fly63.com">www.fly63.com</a></p>
    </footer>
  </body>
</html>

链接: https://www.fly63.com/course/15_844