Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Angular 2 form


May 08, 2021 Angular2


Table of contents


Describe

In this chapter, we'll learn how to create a form. We'll use the following classes and instructions in our example.

  • Form-group, form-control, and btn classes from Bootstrap.

  • NgControl instructions for data binding and NgControl for tracking our control status.

  • NgControl is one of the NgForm instruction family that validates and tracks form elements.

  • The ngSubmit pseudo-instruction is used to process the submission of the form.

Example

The following example describes how to create a form in Angle 2:

<html>
  <head>
    <title>Contact Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="external nofollow" target="_blank" >
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/es6-shim.min.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2-polyfills.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/system.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/typescript.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/Rx.js"></script>
    <script src="https://atts.w3cschool.cn/attachments/tuploads/angular2/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/main')
            .then(null, console.error.bind(console));
    </script>

  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

The above code includes the following configuration options:

  • You can configure index files using the .html version. SystemJS converts TypeScript to JavaScript before running the application using the transpiler option.

  • If you don't translate to JavaScript before you run your application, you may see compiler warnings and errors hidden in your browser.

  • TypeScript generates metadata for each class of your code when you set the emitDecorator Metadata option. If you do not specify this option, a large amount of unused metadata is generated, which affects the file size and the application runtime.

  • Angular 2 includes packages from the app folder, Chinese will have a .ts extension.

  • Next it loads the main component file from the application folder. If the primary component file is not found, it displays an error in the console.

  • When Angula called the boot function in main.ts, it reads the Company metadata, finds the "app" selector, finds an element label named app, and loads the application between those tags.

To run the code, you need the following TypeScript (.ts) file, which you need to save under the application folder.

form_main.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from "./data_binding_app.component";

bootstrap(AppComponent);
contact.ts
export class Contact {
  constructor(
    public firstname: string,
    public lastname: string,
    public country: string,
    public phone: number
  ) {  }
}

The Contact class contains the first name, last name, country, and phone number used in our form.

forms_app.component.ts
import {Component} from 'angular2/core';
import {ContactComponent} from './contact-form.component'
@Component({
  selector: 'my-app',
  template: '',
  directives: [ContactComponent]
})
export class AppComponent { }
  • @Component is an decorator that uses configuration objects to create components.

  • The selector creates an instance of the component and finds the tag in the parent HTML.

  • The template tells Angular to render as a view.

  • The app.component.ts above will import the ContactComponent component and use instructions to contain the component.

contact-form.component.ts
import {Component} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import { Contact } from './contact';
@Component({
  selector: 'contact-form',
  templateUrl: 'app/contact-form.component.html'
})
export class ContactComponent {
  countries = ['India', 'Australia', 'England', 'South Africa', 'USA', 'Japan', 'Singapore'];
  contact = new Contact('Ravi', 'Shankar', this.countries[0], 6445874544);
  submitted = false;
  onSubmit() { this.submitted = true; }
  active = true;
  newContact() {
    this.contact = new Contact('', '');
    this.active = false;
    setTimeout(()=> this.active=true, 0);
  }
}
  • Import NgForm, which provides CSS class and model state.

  • The templateUrl property provides the path to the .html of the object file, which contains our form elements.

  • The onSubmit() method changes the committed value to true after the call, and newContact() creates a new contact.

contact-form.component.html
<div class="container">
  <div [hidden]="submitted">
    <h2>Contact Form</h2>
    <form *ngIf="active" (ngSubmit)="onSubmit()" #contactForm="ngForm" novalidate>
      <div class="form-group">
        <label for="firstname">First Name</label>
        <input type="text" class="form-control" placeholder="Enter Your First Name" required
          [(ngModel)]="contact.firstname"
            ngControl="firstname"  #firstname="ngForm" >
        <div [hidden]="firstname.valid || firstname.pristine" class="alert alert-danger">
          firstname is required
        </div>
      </div>
      <div class="form-group">
        <label for="lastname">Last Name</label>
        <input type="text" class="form-control" placeholder="Enter Your Last Name"
          [(ngModel)]="contact.lastname"
            ngControl="lastname" >
      </div>
      <div class="form-group">
        <label for="country">Country</label>
        <select class="form-control" required
          [(ngModel)]="contact.country"
            ngControl="country" #country="ngForm" >
          <option value="" selected disabled>Select Your Country</option>
          <option *ngFor="#coun of countries" [value]="coun">{{coun}}</option>
        </select>
        <div [hidden]="country.valid || country.pristine" class="alert alert-danger">
          Country is required
        </div>
      </div>

      <div class="form-group">
         <label for="phone">Phone Number</label>
         <input type="number" class="form-control" placeholder="Enter Your Phone Number"
            [(ngModel)]="contact.phone"
            ngControl="phone"
         >
      </div>

      <button type="submit" class="btn btn-primary" [disabled]="!contactForm.form.valid">Submit</button>
      <button type="button" class="btn btn-primary" (click)="newContact()">New Contact</button>
    </form>
  </div>
  <div [hidden]="!submitted">
    <h2>Your contact details :</h2>
    <div class="well">
        <div class="row">
          <div class="col-xs-2">First Name</div>
          <div class="col-xs-10  pull-left">{{ contact.firstname }}</div>
        </div>
        <div class="row">
          <div class="col-xs-2">Last Name</div>
          <div class="col-xs-10 pull-left">{{ contact.lastname }}</div>
        </div>
        <div class="row">
          <div class="col-xs-2">Country</div>
          <div class="col-xs-10 pull-left">{{ contact.country }}</div>
        </div>
        <div class="row">
        <div class="col-xs-2">Phone Number</div>
        <div class="col-xs-10 pull-left">{{ contact.phone }}</div>
      </div>
        <br>
        <button class="btn btn-primary" (click)="submitted=false">Edit Contact</button>
    </div>
  </div>
</div>
  • The code above contains the form, and when the form is submitted, the ngSubmit instruction calls the onSubmit() method.

  • When the submission is set to false, contact details are displayed.

  • It uses the original and valid validation form to enter elements.

  • The ngIf directive checks whether the active object is set to true to display the form.

Output

Let's take the following steps to see how the code above works:

  • Save the HTML code above as an index .html file, as we created in the Environment section, and use the application folder above that contains the .ts file.

  • Open the terminal window and enter the following command:

    npm start
  • Later, the browser tab should open and display the output, as shown below.

Or you can run the file in another way:

  • Save the HTML code above as angular2_forms.html file in the server root folder.

  • Open this HTML file as http://localhost/angular2_forms.html and display the output as shown below.

Related articles

OnSubmit event