Latest web development tutorials

AngularJS2 form

This chapter we will introduce how to use the components to build a template and Angular form.

Angular use the template, we can create all types of forms, for example: login form, contact form, form and other details of goods, and we can add data validation for these form fields.

Next we step by step to achieve the functionality of forms.


Create Project

Import project initialization.

Create a complete project can refer to: AngularJS2 typescript environment configuration

Upon completion, we performcnpm install to load dependencies.

Create Site Model

The following creates a simple model class Site, contains three required fields: id, name, url, an optional field: alexa.

Create site.ts file in the angular-forms / app directory, as follows:

app / site.ts file:

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

The following code, marked as public for the public field, alexa After adding a question mark (?) Indicates optional fields.

Create a form component

Angular Each form is divided into two parts: an HTML-based templates, and a code-based component, which is used to process the data and user interaction.

Create a site-form.component.ts file in the angular-forms / app directory, as follows:

app / site-form.component.ts file:

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.w3big.com', ' www.google.com', 'www.taobao.com', 'www.facebook.com']; model = new Site (1, 'tutorial', this urls [0], 10000.); Submitted = false; onSubmit () { . this submitted = true;} // TODO: Remove completed get diagnostic () { return . JSON stringify (this model.) ;} }

Component instances introduced decorators and Site model.

@Component Selector "site-form" means that we can be a<site-form> tag, put this form into the parent template.

templateUrl attribute points to a separate HTML template files, called site-form.component.html.

diagnostic property is used to return JSON form of this model.

Root application module definition

Modify app.module.ts to define the application of the root module, the module can be specified in the reference to the external part of this statement and module components, such SiteFormComponent.

Because the template-driven forms have their own module, so we have to add an array FormsModule to imports of the application, so that we can use the form.

app / app.module.ts file code is as follows

app / app.module.ts file:

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 { }

Create a root component

Modify the root component files app.component.ts, will SiteFormComponent will be placed therein.

app / app.component.ts file:

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

Create an initial HTML form template

Create a template file site-form.component.html, code as follows:

app / site-form.component.html file:

<Div class = "container"> <H1> Website Forms </ h1> <Form> <Div class = "form-group"> <Label for = "name"> website name </ label> <Input type = "text" class = "form-control" id = "name" required> </ Div> <Div class = "form-group"> <Label for = "alterEgo"> alexa ranking </ label> <Input type = "text" class = "form-control" id = "alexa"> </ Div> <Button type = "submit" class = "btn btn-default" > Submit </ button> </ Form> </ Div>

required property is set to the field is required, if not set it is optional.

Enter the following command at the angular-forms directory:

cnpm install bootstrap --save

Open the index.html file, add the following style link to the <head>:

<Link rel = "stylesheet" href = "node_modules / bootstrap / dist / css / bootstrap.min.css">

After executingnpm start, visit: http: // localhost: 3000 / , output results are as follows:


Two-way data binding using ngModel

Next we use ngModel two-way data binding, by listening to the DOM event to achieve the properties of the updated components.

Modify app / site-form.component.html, use our form ngModel bound to the model. Code as follows:

app / site-form.component.html file:

<Div class = "container"> <H1> Website Forms </ h1> <Form> {{diagnostic}} <div class = "form-group"> <Label for = "name"> website 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 ranking </ label> <Input type = "text" class = "form-control" id = "alexa" [(ngModel )] = "model.alexa" name = "alexa"> </ Div> <Div class = "form-group"> <Label for = "url"> Website 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" > Submit </ button> </ Form> </ Div>
  • Each input element has an id attribute, which is the label for the element attribute is used to match the label to the corresponding input.

  • Each input element has a name attribute, Angular form modules need to use it as a form registration controller.

Run the above example output results are as follows:

{{diagnostic}} just for testing when output data use.

We can also track the status by modifying ngModel and validation, which uses three CSS classes to update the control to reflect the current status.

status When the true class False when class
Control has been visited ng-touched ng-untouched
Control values ​​have changed ng-dirty ng-pristine
Control values ​​are valid ng-valid ng-invalid

So that we can add custom CSS to reflect the state of the form.

Create forms.css file in the directory angular-forms, as follows:

forms.css file:

.ng-valid [required], .ng -valid .required { border-left: 5 px solid # 42A948 ; / * Green * / } .ng-invalid: not (form) { border-left: 5 px solid # a94442 ; / * Red * / }

Open the index.html file, add the following style link to the <head>:

<Link rel = "stylesheet" href = "forms.css">

Modify app / site-form.component.html, code as follows:

app / site-form.component.html file:

<Div class = "container"> <H1> Website Forms </ h1> <Form> {{diagnostic}} <div class = "form-group"> <Label for = "name"> website 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" > website name is required </ div> </ Div> <Div class = "form-group"> <Label for = "alexa"> alexa ranking </ label> <Input type = "text" class = "form-control" id = "alexa" [(ngModel )] = "model.alexa" name = "alexa"> </ Div> <Div class = "form-group"> <Label for = "url"> Website 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" > Submit </ button> </ Form> </ Div>

Template by hidden attribute of the div element is bound to the property name of the control, we can control the visibility of the "name" field of the error message.

Delete the data field name, and display the results as follows:

Add a website

Next we create a form for adding sites, in app / site-form.component.html add a button:

app / site-form.component.html file:

<Button type = "button" class = "btn btn-default" (click) = "newSite ()"> Add sites </ button>

The above-button event bound to the component method:

app / site-form.component.ts file:

active = true; newSite () { this. model = new Site (5, '', ' ');. This active = false; setTimeout (. () => This active = true, 0);}

We add a component to the active tag, initialize it to true. When we add a new hero, it is the active flag is set to false, then a quick setTimeout function quickly set it back to true.

To submit the form by ngSubmit

We can use Angular NgSubmit instructions to submit the form, and through the event binding mechanism bind it to SiteFormComponent.submit () method on.

<Form * ngIf = "active" (ngSubmit) = "onSubmit ()" # siteForm = "ngForm">

We define a template variable reference #siteForm, and initialize it to "ngForm".

This siteForm variable now refers NgForm instruction, it represents a form of the whole.

site-form.component.ts file complete code is as follows:

app / app.component.ts file:

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.w3big.com', ' www.google.com', 'www.taobao.com', 'www.facebook.com']; model = new Site (1, 'tutorial', this urls [0], 10000.); Submitted = false; onSubmit () { . this submitted = true;} // TODO: Remove completed 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 complete code is as follows:

app / site-form.component.html file:

<Div class = "container"> <Div [hidden] = "submitted "> <H1> Website Forms </ h1> <Form * ngIf = "active" (ngSubmit) = "onSubmit ()" # siteForm = "ngForm"> {{diagnostic}} <div class = "form-group"> <Label for = "name"> website 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" > website name is required </ div> </ Div> <Div class = "form-group"> <Label for = "alexa"> alexa ranking </ label> <Input type = "text" class = "form-control" id = "alexa" [(ngModel )] = "model.alexa" name = "alexa"> </ Div> <Div class = "form-group"> <Label for = "url"> Website 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"> Submit </ button> <Button type = "button" class = "btn btn-default" (click) = "newSite ()"> Add Site </ button> </ Form> </ Div> <Div [hidden] = "! Submitted"> <H2> information you submit as follows: </ h2> <Div class = "row"> <Div class = "col-xs-3 "> website name </ div> <Div class = "col-xs-9 pull-left"> {{model.name}} </ div> </ Div> <Div class = "row"> <Div class = "col-xs-3 "> website alexa ranking </ div> <Div class = "col-xs-9 pull-left"> {{model.alexa}} </ div> </ Div> <Div class = "row"> <Div class = "col-xs-3 "> Website URL </ div> <Div class = "col-xs-9 pull-left"> {{model.url}} </ div> </ Div> <Br> <Button class = "btn btn-default" (click) = "submitted = false"> Edit </ button> </ Div> </ Div>

We attribute the hidden template bound to SiteFormComponent.submitted property.

The main form is visible from the start, as submitted property is false, when we submitted this form is hidden, submitted attribute is true:

submitted = false; onSubmit () { . this submitted = true;}

The final directory structure:

As used herein, the source code can be downloaded in the following ways, and does not contain node_modules typings directory.

Demo GIf complete example follows: