Angular 2 Form表单

Angular 2 Form表单

在angular2 form表单中我们需要了解表单数据绑定、数据验证、数据提交等内容,在下面的示例中并没有实际提交到后台,这部分内容在今后webapi中加以练习。

表单建立

<form (ngSubmit)="onSubmit(planetForm.value)" #planetform="ngForm">

</form>

这里是一个空的表单ngSubmit是一个事件,用于提交数据,数据则是整个form表单的内容,通常情况下我们的表单会绑定到我们的一个model中,那么提交的数据最后也是以json格式返回到后台来处理。

在表单中我们可以使用标准的html5控件来处理用户输入。

数据绑定

<div class="form-group">

        <label class="col-xs-4 control-label" for="id">id : </label>

        <div class="col-xs-8">

            <input type="text" style="width300px" class="form-control" required

                   [(ngModel)]="myPlanet.id"

                   ngControl="id"

                   #planetid="ngForm">

            <div [hidden]="planetid.valid || planetid.pristine" class="alert alert-danger">

                The Name of green car is required !

            </div>

        </div>

    </div>

这个一个表单输入的内容其中使用的是bootstrap的表单样式,在input中我们使用[(ngModel)](注意大小写)实现双向绑定,ngControl用于检测数据变化对应的是model中的字段,设置input的变量为ngForm来告诉angular 这个输入是这个表单内容。在vs中由于默认设置在粘贴html文本时会自动将大写字母变化成小写字母,所以angular的某些标签很容易发生错误,所以需要关闭这个自动转换,方法就是在vs的选项中将文本编辑器中的html高级选项下的粘贴时设置格式设置为false。

数据验证

html5内置的数据验证包括Required、minLength、maxLength、pattern ,我们可以将这些标签应用到我们的输入控件上,如

<input type="text" style="width300px" class="form-control" required maxlength="10" minLength="4"

                   [(ngModel)]="myPlanet.id"

                   ngControl="name"

                   #planetid="ngForm">

            <div [hidden]="planetid.valid || planetid.pristine" class="alert alert-danger">

                The id is required !

            </div>

这里的"planetid.valid || planetid.pristine是验证这个input输入是否有效,或者数据是否改变。

Formbuilder

Formbuilder是我们可以采用的另一种方式来创建Form,这种方式是以模型驱动完成的,更适合我们进行编码控制,有利于我们将逻辑与视图分离。

Angular2 form 作用机制由两个主要的组件Controls和Controlsgroup。

Control:包含值和验证状态,一个control能够被邦定可以包含三个可选参数(缺省值,验证,异步验证),例如

this.username = new Control('Default value', Validators.required, usernameValidator.checkIfAvailable);

在html应用时使用ngControl标签绑定这个控件

<input required type=”text”ngControl=”username” />

 

这里定义的username与input中ngControl指定的名称要一致。

Control Groups:form定义的一部分,通过将多个cotrol组合在一起形成组。

class App {
 
 name: Control;
 username: Control;
 email: Control;
 
 form: ControlGroup;
 
 constructor(private builder:FormBuilder) {
 
   this.name = new Control('',Validators.required);
   this.email = new Control('',Validators.required);
   this.username = new Control('',Validators.required);
 
   this.form = builder.group({
     name: this.name,
     email: this.email,
     username: this.username
   });
 }

};

html应用时加入ngFormModel来标识。

<form [ngFormModel]=”form”>

自定义验证

除了内置验证外,我们还可以自定义验证,例子如下

import {Control} from 'angular2/common';

interface ValidationResult

{

    [key: string]: boolean;

}

export class UsernameValidator

{

 

static startsWithNumber( control: Control ): ValidationResult

    {

 

        if ( control.value !="" && !isNaN( control.value.charAt( 0 ) ) ){

            return { "startsWithNumber"true };

        }

        return null;

    }

}

这个自定义验证如果输入的值中首字母是数字则验证无效,返回null则验证通过。使用方法

首先import {UsernameValidator} from './customValidate';

然后在我们需要验证的控件上加入自定义验证

this.name = new Control( this.myPlanet.name, UsernameValidator.startsWithNumber );

错误提示

<div *ngIf="name.dirty && !name.valid">

  <p *ngIf="name.errors.startsWithNumber">

    Your name can't start with a number

  </p>

</div>

这里的errors. startsWithNumber就是我们自定义返回的key值。最好的方式是使用hasError,因为如果返回的startsWithNumber是null的话会引发异常

<p *ngIf="name.hasError('startsWithNumber')">

异步验证

如果我们需要使用service去到后台获取数据并验证,则我们需要使用异步验证方式,这里的例子使用promise模拟。

static usernameTaken( control: Control ): Promise<ValidationResult>

    {

 

        let q = new Promise(( resolve, reject ) =>

        {

            setTimeout(() =>

            {

                if ( control.value !== 'oldkingsir') {

                resolve( { "usernameTaken"true});

            } else {

resolve( null );

            }

        }, 1000 )

    });

 

   return q;

 }

真实应用可能是

classProductValidator {

    staticproductExists(control: Control): {[key: string]: any} {

        returnnew Promise( resolve => {

            varproductService = new ProductService();

            varproduct: Product;

            productService.getProduct(control.value)

            .then(productFound=> {

                if(productFound == null) {

                    //need to return something if not ok

                    resolve({productExists:false});

                }else {

//need to return null if ok

                    resolve(null);

                }

            });

        });

    }

}

下面需要使用验证的第三个参数,方式如下

this.name = new Control( this.myPlanet.name,UsernameValidator.startsWithNumber, UsernameValidator.usernameTaken );

html

<div *ngIf="name.dirty && !name.valid">

<span *ngIf="name.pending">Checking istaken...</span>

                  <p *ngIf="name.hasError('startsWithNumber')">

                    Your name can't start with a number

                 </p>

                <p *ngIf="name.hasError('usernameTaken')">

                    Your name is already taken

                 </p>

            </div>

这里使用了pending来友好提示验证中。

组合验证

如果需要进行多个验证可以使用compose组合验证,如下

this.name = new Control('',Validators.compose([Validators.required, Validators.minLength(4)]));

猜你喜欢

转载自blog.csdn.net/lmy_1/article/details/54425202