ANGULARJS2 Study Notes (vi) Form

Source: Internet
Author: User
Tags export class

Angular 2 Form form

In the Angular2 form form we need to understand the form data binding, data validation, data submission and so on, in the following example is not actually submitted to the background, this part of the content in the future Webapi to practice.

Form creation

<form (Ngsubmit) = "OnSubmit (planetform.value)" #planetform = "Ngform" >

</form>

Here is an empty form Ngsubmit is an event for submitting data, the data is the content of the entire form form, and usually our form is bound to one of our model, then the submitted data is finally returned to the background in JSON format for processing.

In the form we can use the standard HTML5 controls to handle user input.

Data binding

<div class= "Form-group" >

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

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

<input type= "text" style= "width:300px" 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>

This one of the form input uses the bootstrap form style, in input we use [(Ngmodel)] (note case) to implement two-way binding, Ngcontrol for detecting data changes corresponding to the field in the model, Set the variable of input to Ngform to tell angular that this input is the form content. In VS, because the default setting will automatically change uppercase letters to lowercase letters when pasting HTML text, some of the angular tags are prone to errors, so you need to turn this auto-conversion off. The method is to set the paste-time format to false under the HTML Advanced option in the text editor in the VS option.

Data validation

HTML5 built-in data validation includes required, MinLength, maxLength, andpattern , which we can apply to our input controls, such as

<input type= "text" style= "width:300px" class= "Form-control" required maxlength= "ten" minlength= "4"

[(Ngmodel)]= "Myplanet.id"

Ngcontrol= "Name"

#planetid = "Ngform" >

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

The ID is required!

</div>

Here's "Planetid.valid | | Planetid.pristine is to verify that the input inputs are valid, or that the data is changed.

Formbuilder

Formbuilder is another way we can create forms, which is done by model-driven, which is more suitable for us to encode control, which allows us to separate the logic from the view.

ANGULAR2 form action mechanism consists of two main components controls and controls group.

Control: Contains the value and validation state, a control can be set to include three optional parameters (default, validation, asynchronous authentication), such as

This.username = new Control (' Default value ', validators.required, usernamevalidator.checkifavailable);

Use the Ngcontrol tag to bind the control in an HTML app

<input Required type= "text" ngcontrol= "username"/>

The username defined here is consistent with the name specified in input Ngcontrol.

Control Groups : Form defined as part of the Cotrol by adding multiple grouped together to form a group.

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
});
}

};

The HTML app is joined by Ngformmodel to identify.

<form [ngformmodel]= "Form" >

Custom validation

In addition to the built-in verification, we can also customize the validation, examples are as follows

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;

}

}

This custom validation verifies if the first letter in the input value is a number and the validation is not valid and returns NULL. How to use

First import {Usernamevalidator} from './customvalidate ';

Then add custom validation to the controls we need to validate

THIS.name = new Control (This.myPlanet.name, Usernamevalidator.startswithnumber);

Error hints

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

<p *ngif= "Name.errors.startsWithNumber" >

Your name can ' t start with a number

</p>

</div>

Here's the errors. Startswithnumber is the key value returned by our custom. The best way to do this is to use Haserror, because if the returned startswithnumber is NULL, an exception is thrown

<p *ngif= "Name.haserror (' Startswithnumber ')" >

Asynchronous validation

If we need to use the service to get the data in the background and verify it, we need to use the asynchronous authentication method, where the example uses the Promise simulation.

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;

}

The real application may be

Class Productvalidator {

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

return new Promise (resolve = {

var productservice = new Productservice ();

var product: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);

}

});

});

}

}

The following is the third parameter to use for validation, in the following way

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>

The pending is used here for friendly hints validation.

Combination validation

If more than one validation is required, you can use compose combination validation, as follows

THIS.name = new Control ("', Validators.compose ([Validators.required, Validators.minlength (4)]));

Finally, if the entire form validation does not pass through we do not commit it can be processed on the submit button, as

<button type= "Submit" class= "btn btn-default" [disabled]= "!form.valid" >Submit</button>

ANGULARJS2 Study Notes (vi) Form

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.