Runoob Tutorial ArchiveEnglish

Angular 2 Forms

Angular 2 Forms

In this chapter, we will introduce how to build an Angular form using components and templates.

Using Angular templates, we can create various types of forms, such as login forms, contact forms, product detail forms, etc., and we also add data validation to the fields of these forms.

Next, we will implement the form functionality step by step.


Create Project

Import the initialized project.

For a complete project creation, please refer to:Angular 2 TypeScript environment configuration

Or download the source code directly:Click here to download

After unzipping, rename the directory to angular-forms, and modify the"name": "angular-quickstart"in the angular-forms/package.json fileto"name": "angular-forms"

After completion, we executecnpm installto load the dependency packages.

Create the Site model

Below, a simple model class Site is created, which includes three required fields: id, name, url, and one optional field: alexa.

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

app/site.ts file:

export

class

Site

{

constructor

(

public

id

:

number

,

public

name

:

string

,

public

url

:

string

,

public

alexa

?:

number

)

{

}

}

In the following code, fields marked as public are public fields, and adding a question mark (?) after alexa indicates an optional field.

Create a form component

Each Angular form consists of two parts: an HTML-based template and a code-based component that handles data and user interaction.

Create the site-form.component.ts file in the angular-forms/app directory, the code is 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.runoob.com

'

,

'

www.google.com

'

,

'

www.taobao.com

'

,

'

www.facebook.com

'

]

;

model

=

new

Site

(

1

,

'

Beginner Tutorial

'

,

this

.

urls

[

0

]

,

10000

)

;

submitted

=

false

;

onSubmit

(

)

{

this

.

submitted

=

true

;

}

//

TODO: Remove after completion

get

diagnostic

(

)

{

return

JSON

.

stringify

(

this

.

model

)

;

}

}

The Component decorator and Site model are imported in the instance.

The @Component selector "site-form" indicates that we can throw this form into a parent template using atag.

The templateUrl property points to a separate HTML template file named site-form.component.html.

The diagnostic property is used to return this model in JSON format.

Define the root module of the application.

Modify app.module.ts to define the root module of the application, specifying the external modules referenced and the components declared in this module, such as SiteFormComponent.

Because template-driven forms have their own module, we must add FormsModule to this application's imports array so that we can use forms.

The code for the app/app.module.ts file 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 root component

Modify the root component file app.component.ts and place SiteFormComponent in it.

app/app.component.ts file:

import

{

Component

}

from

'

@angular/core

'

; @

Component

(

{

selector

:

'

my-app

'

,

template

:

'

'

}

)

export

class

AppComponent

{

}

Create an initial HTML form template

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

app/site-form.component.html file:

<
div
class
=
"
container
"
<
h1

Website Form

</
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
=
"
alexa
"

alexa ranking

</
label
<
input
type
=
"
text
"
class
=
"
form-control
"
id
=
"
alexa
"
</
div
<
button
type
=
"
submit
"
class
=
"

btn btn-default

"

Submit

</
button
</
form
</
div

Fields with the required attribute set are required fields; if not set, they are optional.

Enter the following command in the angular-forms directory:


cnpm install bootstrap --save

Open the index.html file and add the following style link to the middle:

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

Executenpm startThen, access: http://localhost:3000/, and the output effect is as follows:

3D C3 3A 49 45 5 9F54 DED865EE4D9


Use ngModel for two-way data binding

Next, we use ngModel for two-way data binding to achieve component property updates by listening to DOM events.

Modify app/site-form.component.html, and use ngModel to bind our form to the model. The code is as follows:

app/site-form.component.html file:

<
div
class
=
"
container
"
<
h1

Website Form

</
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

Every input element has an id attribute, which is used by the for attribute of the label element to match the label to the corresponding input.

  • Every input element has a name attribute, which the Angular form module uses to register a controller for the form.

  • Running the above instance outputs the following:

    77D976BB EF 41CD B539 3F6 91D38EA

    **{{diagnostic}} ** is only used for outputting data during testing.

    We can also track modification status and validity validation using ngModel, which uses three CSS classes to update the control to reflect the current state.

    State Class when true Class when false
    The control has been visited ng-touched ng-untouched
    Control value has changed ng-dirty ng-pristine
    Control value is valid ng-valid ng-invalid

    This allows us to add custom CSS to reflect the form state.

    Create the forms.css file in the angular-forms directory, the code is 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 and add the following style link to:

    <
    link
    rel
    =
    "
    stylesheet
    "
    href
    =
    "
    forms.css
    "

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

    app/site-form.component.html file:

    <
    div
    class
    =
    "
    container
    "
    <
    h1

    Website Form

    </
    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

    By binding the hidden attribute of the div element to the property of the name control in the template, we can control the visibility of the error message for the "name" field.

    Deleting the data in the name field shows the following result:

    815B D4E 8 19 445B 9 A3 BD C9 BCB B

    Add a website

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

    app/site-form.component.html file:

    <
    button
    type
    =
    "
    button
    "
    class
    =
    "

    btn btn-default

    "

    (

    click

    )=

    "

    newSite()

    "

    Add website

    </

    button

    Bind the above button event 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 an active marker to the component and initialize it to true. When we add a new site, it sets the active marker to false, and then quickly sets it back to true using a setTimeout function.

    Submit the form using ngSubmit

    We can use Angular's NgSubmit directive to submit the form and bind it to the SiteFormComponent.submit() method through the event binding mechanism.

    <
    form
    ngIf
    =
    "
    active
    "
    (
    ngSubmit
    )=
    "
    onSubmit()
    "
    siteForm
    =
    "
    ngForm
    "

    We defined a template reference variable #siteForm and initialized it to "ngForm".

    This siteForm variable now references the NgForm directive, which represents the entire form.

    The complete code for site-form.component.ts is 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.runoob.com

    '

    ,

    '

    www.google.com

    '

    ,

    '

    www.taobao.com

    '

    ,

    '

    www.facebook.com

    '

    ]

    ;

    model

    =

    new

    Site

    (

    1

    ,

    '

    Beginner Tutorial

    '

    ,

    this

    .

    urls

    [

    0

    ]

    ,

    10000

    )

    ;

    submitted

    =

    false

    ;

    onSubmit

    (

    )

    {

    this

    .

    submitted

    =

    true

    ;

    }

    //

    TODO: Remove after completion

    get

    diagnostic

    (

    )

    {

    return

    JSON

    .

    stringify

    (

    this

    .

    model

    )

    ;

    }

    active

    =

    true

    ;

    newSite

    (

    )

    {

    this

    .

    model

    =

    new

    Site

    (

    5

    ,

    '

    '

    ,

    '

    '

    )

    ;

    this

    .

    active

    =

    false

    ;

    setTimeout

    (

    (

    )

    =>

    this

    .

    active

    =

    true

    ,

    0

    )

    ;

    }

    }

    The complete code for app/site-form.component.html is as follows:

    app/site-form.component.html file:

    <
    div
    class
    =
    "
    container
    "
    <
    div
    [
    hidden
    ]=
    "
    submitted
    "
    <
    h1

    Website Form

    </
    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 website

    </
    button
    </
    form
    </
    div
    <
    div
    [
    hidden
    ]=
    "
    !submitted
    "
    <
    h2

    The information you submitted is 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
    "

    Alexa website 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

    In the template, we bind the hidden attribute to the SiteFormComponent.submitted property.

    The main form is visible from the start because the submitted property is false, and it is hidden when we submit the form, and the submitted property is true:

    submitted

    =

    false

    ;

    onSubmit

    (

    )

    {

    this

    .

    submitted

    =

    true

    ;

    }

    The final directory structure is as follows:

    C397C 61 C9 4616 9 68 3676A 87F69

    The source code used in this article can be downloaded in the following way, and does not include the node_modules and typings directories.

    Download source code

    The complete instance demonstration GIF is as follows:

    angular