AngularJS2 表单

来源:互联网 发布:sql内连接和外连接 编辑:程序博客网 时间:2024/05/17 06:50
一、创建项目
1. 项目初始化
2. 创建 Site 模型
以下创建了一个简单的模型类 Site,包含了三个必需字段:id,name,url,一个可选字段:alexa。
app/site.ts 文件:
export class Site {  constructor(    public id: number,    public name: string,    public url: string,    public alexa?: number  ) {  }}
3. 创建一个表单组件
每个 Angular 表单分为两部分:一个基于 HTML 的模板和一个基于代码的组件,它用来处理数据和用户交互。
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.runoob.com', 'www.google.com',            'www.taobao.com', 'www.facebook.com'];  model = new Site(1, 'AngularJS2教程', this.urls[0], 10000);  submitted = false;  onSubmit() { this.submitted = true; }  // TODO: 完成后移除  get diagnostic() { return JSON.stringify(this.model); }}
@Component 选择器 "site-form" 表示我们可以通过一个 <site-form> 标签,把此表单扔进父模板中。
diagnostic 属性用于返回这个模型的JSON形式。
4. 定义应用的根模块
app/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 { }
5. 创建根组件
app/app.component.ts 文件:
import { Component } from '@angular/core'; @Component({  selector: 'my-app',  template: '<site-form></site-form>'})export class AppComponent { }
6. 创建一个初始 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>
在 angular-forms 目录下输入以下命令:
cnpm install bootstrap --save
打开 index.html 文件,把以下样式链接添加到 <head> 中:
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
执行 npm start 后,访问:http://localhost:3000/,输出效果如下:

二、使用 ngModel 进行双向数据绑定
修改 app/site-form.component.html文件 ,使用 ngModel 把表单绑定到模型。
app/site-form.component.html 文件:
<div class="container">    <h1>网站表单</h1>    <form>      {{diagnostic}}      <div class="form-group">        <label for="name">网站名</label>       <input type="text" class="form-control" id="name"         required         [(ngModel)]="model.name" name="name">      </div>      <div class="form-group">        <label for="alexa">alexa 排名</label>         <input type="text"  class="form-control" id="alexa"         [(ngModel)]="model.alexa" name="alexa">      </div>      <div class="form-group">        <label for="url">网站 URL </label>        <select class="form-control"  id="url"                required                [(ngModel)]="model.url" name="url">          <option *ngFor="let p of urls" [value]="p">{{p}}</option>        </select>      </div>      <button type="submit" class="btn btn-default">提交</button>    </form></div>
  • 每一个 input 元素都有一个 id 属性,它被 label 元素的 for 属性用来把标签匹配到对应的 input 。
  • 每一个 input 元素都有一个 name 属性, Angular 的表单模块需要使用它为表单注册控制器。

运行以上实例输出结果如下:


添加自定义CSS来反映表单的状态,在 angular-forms 目录下创建 forms.css 文件:
.ng-valid[required], .ng-valid.required  {  border-left: 5px solid #42A948; /* green */} .ng-invalid:not(form)  {  border-left: 5px solid #a94442; /* red */}
修改 app/site-form.component.html文件如下:
<div class="container">    <h1>网站表单</h1>    <form>      {{diagnostic}}      <div class="form-group">        <label for="name">网站名</label>          <input type="text" class="form-control" id="name"               required               [(ngModel)]="model.name" name="name"               #name="ngModel" >        <div [hidden]="name.valid || name.pristine"              class="alert alert-danger">          网站名是必需的        </div>      </div>      <div class="form-group">        <label for="alexa">alexa 排名</label>         <input type="text"  class="form-control" id="alexa"         [(ngModel)]="model.alexa" name="alexa">      </div>      <div class="form-group">        <label for="url">网站 URL </label>        <select class="form-control"  id="url"                required                [(ngModel)]="model.url" name="url">          <option *ngFor="let p of urls" [value]="p">{{p}}</option>        </select>      </div>      <button type="submit" class="btn btn-default">提交</button>    </form></div>
模板中通过把 div 元素的 hidden 属性绑定到 name 控件的属性,就可以控制"name"字段错误信息的可见性了。
删除掉 name 字段的数据,显示结果如下所示:

1. 添加一个网站

在 app/site-form.component.html 添加一个按钮:

<button type="button" class="btn btn-default" (click)="newSite()">添加网站</button>

将以上按钮事件绑定到组件方法上:
active = true; newSite() {  this.model = new Site(5, '', '');  this.active = false;  setTimeout(() => this.active = true, 0);}
2. 通过 ngSubmit 来提交表单
使用 Angular 的指令 NgSubmit 来提交表单, 并且通过事件绑定机制把它绑定到 SiteFormComponent.submit() 方法上。
<form *ngIf="active" (ngSubmit)="onSubmit()" #siteForm="ngForm">
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.runoob.com', 'www.google.com',            'www.taobao.com', 'www.facebook.com'];  model = new Site(1, '菜鸟教程', this.urls[0], 10000);  submitted = false;  onSubmit() { this.submitted = true; }  // TODO: 完成后移除  get diagnostic() { return JSON.stringify(this.model); }  active = true;  newSite() {    this.model = new Site(5, '', '');    this.active = false;    setTimeout(() => this.active = true, 0);  }}
app/site-form.component.html 完整代码如下:
<div class="container">  <div  [hidden]="submitted">    <h1>网站表单</h1>     <form *ngIf="active" (ngSubmit)="onSubmit()" #siteForm="ngForm">      {{diagnostic}}      <div class="form-group">        <label for="name">网站名</label>        <input type="text" class="form-control" id="name"               required               [(ngModel)]="model.name" name="name"               #name="ngModel" >        <div [hidden]="name.valid || name.pristine"              class="alert alert-danger">          网站名是必需的        </div>      </div>      <div class="form-group">        <label for="alexa">alexa 排名</label>         <input type="text"  class="form-control" id="alexa"         [(ngModel)]="model.alexa" name="alexa">      </div>      <div class="form-group">        <label for="url">网站 URL </label>        <select class="form-control"  id="url"                required                [(ngModel)]="model.url" name="url">          <option *ngFor="let p of urls" [value]="p">{{p}}</option>        </select>      </div>      <button type="submit" class="btn btn-default" [disabled]="!siteForm.form.valid">提交</button>      <button type="button" class="btn btn-default" (click)="newSite()">新增网站</button>    </form></div> <div [hidden]="!submitted">    <h2>你提交的信息如下:</h2>    <div class="row">      <div class="col-xs-3">网站名</div>      <div class="col-xs-9  pull-left">{{ model.name }}</div>    </div>    <div class="row">      <div class="col-xs-3">网站 alexa 排名</div>      <div class="col-xs-9 pull-left">{{ model.alexa }}</div>    </div>    <div class="row">      <div class="col-xs-3">网站 URL </div>      <div class="col-xs-9 pull-left">{{ model.url }}</div>    </div>    <br>    <button class="btn btn-default" (click)="submitted=false">编辑</button>  </div></div>
最终的目录结构为:
angular-forms
app
app.component.ts
app.module.ts
main.ts
site.ts
site-form.component.html
site-form.component.ts

node_modules...
typings...
form.css
index.html
package.json
styles.css
systemjs.config.json
tsconfig.json
typings.json



0 0
原创粉丝点击