Building Angular Form App in Easy Steps
Angular Form App

Building Angular Form App in Easy Steps


In this article we are going to create an angular form application. We will be using Angular features like 2 way data binding to update the data as it changes in the form and vice -versa

In this article we will be using Angular template driven forms to build the forms application.

You can build almost any kind of form with Angular, business forms, login and sign up and any other form of your choice.

Introduction

In this article we will be building Angular Forms using the steps below:

  1. Creating an Angular form with a template
  2. Creating 2 way data binding with the help of ng-model, where writing input on the form creates a binding that can be tied to the back-end
  3. Using CSS to improve readability and interactivity of the forms
  4. Validate the forms and display error if something is wrong
  5. Using template reference errors to share info between HTML elements.


Scaffolding the App

  1. First we need to set up an Angular application on our computer. For this we need the Node Js and NPM package manager
  2. Once you have NodeJS install the angular CLI using the following commands:

npm install -g @angular/cli        

then create the forms app using:

ng new angular-forms-app        

While installing it asks if you need angular routing select NO as of now we don't need angular routing for this application.

to run the app go to the app folder and type the following command

ng serve        

This will serve the application and it will look something like this:

No alt text provided for this image

Now, you have set up the application and it is running on your local machine.

This is a Angular forms tutorial but if you are interested in building Angular Chat Application you can also build that by referring to the article

The template driven forms relay on the forms module. We will be using the following directives to achieve our goal.

The sample form in this guide will use the developer team employment agency to maintain personal information about developers.

Every developer needs a job and has certain skills like full stack javascript developer, python developer, C++ developer etc.

This agency matches the developer with the right job.

No alt text provided for this image

The forms has some features that make it easier to use. The required fields have blue bars to make them stand out and feature that they are required.

There is also a submit button that the developer can press after they have filled out the form.

Working on this form we will be learning

  • How to implement Validation logic
  • Customize the look and feel of the form with CSS
  • Making sure the input is valid and error conditions are handled properly.

If the user skips a mandatory filed or deletes a input after filling it the form displays a validation error and the submit button becomes disabled so as not to allow the form to be submitted unless all the mandatory fields are filled by the developer.

Here are the 5 steps:

  1. Build the Basic Form
  2. Bind the controls of the form with the data using NgModel
  3. Validate input and control the status using the NgModel
  4. Responding to HTML button click by using model data
  5. Handling Form Submission

Building The Form

In the sample form application go to src/app and create a dev.ts file and paste the following code:

export class Dev {


? constructor(
? ? public id: number,
? ? public name: string,
? ? public languagesKnown: string,
? ? public expertise?: string
? ) {? }


}        

This code defines the data model for our form application.

2. The form layout and other details are present in the DevFormComponent

import { Component } from '@angular/core'


import { Dev } from '../dev';


@Component({
? selector: 'app-dev-form',
? templateUrl: './dev-form.component.html',
? styleUrls: ['./dev-form.component.css']
})
export class DevFormComponent {


? powers = ['knows HTML', 'knows CSS', 'knows Angular'


? ];


? model = new Dev(18, 'Dr IQ', this.powers[0]);


? submitted = false;


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


newDev(){
? ? this.model = new Dev(42,'','',);
}


frontEndDev(): Dev { 
? ? const theDev = new Dev(
? ? ? ? 42, 'compDev', 'creates websites on the side',
? ? )
? ? return theDev
}


};        

This tutorial utilizes a demo model and powers. but in the real application you would use a database to save the data and get the data.

4. Next, We need to enable the forms service features and register a created form component.

go to app.module.ts and paste the following code:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';


import { AppComponent } from './app.component';
import { DevFormComponent } from './dev-form/dev-form.component';


@NgModule({
? imports: [
? ? BrowserModule,
? ? CommonModule,
? ? FormsModule
? ],
? declarations: [
? ? AppComponent,
? ? DevFormComponent
? ],
? providers: [],
? bootstrap: [ AppComponent ]
})
export class AppModule { };        

5. The form is displayed in the application layout defined by the root component.

Go to app.component.html and add the dev form selector like:

<app-dev-form></app-dev-form>        

The initial template defines a layout for the form having 2 form groups and a submit button. the form groups defines 2 properties of the Developer data, model, name and skills. Each group has a label and a box for user input

  • The Name attribute has an HTML required attribute
  • The Skill input does not have HTML required attribute.
  • The Submit button has CSS classes for styling.

The sample form uses the classes from twitter bootstrap like container, form-group, form-control and btn.

to use these styles globally import them in the styles.css file

@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');        

7. The form lets the developer choose skills from a list of required list of skills from the agency.

The pre defined list of skills at the agency is part of the data model maintained internally as devFormComponent

The Angular NgForOf directive iterates over the data values to populate the select element.

go to dev-form.componenet.html in the skills section

<div class="form-group">
? <label for="skill">Dev skill</label>
? <select class="form-control" id="skill" required>
? ? <option *ngFor="let lang of skills" [value]="lang">{{lang}}</option>
? </select>
</div>        

Now let us go to the app.component.html and delete the placeholder html from there paste the selector and see the form appear on the page.

<hr>
<style>
? .no-style .ng-valid {
? border-left: 1px ?solid #CCC
}


? .no-style .ng-invalid {
? border-left: 1px ?solid #CCC
}
</style>
<div class="no-style" style="margin-left: 4px">
? <div class="container">
? ? ? <h1>Dev Form</h1>
? ? ? <form>
? ? ? ? <div class="form-group">
? ? ? ? ? <label for="name">Name</label>
? ? ? ? ? <input type="text" class="form-control" id="name" required>
? ? ? ? </div>


? ? ? ? <div class="form-group">
? ? ? ? ? <label for="alsoKnows">Also Knows</label>
? ? ? ? ? <input type="text" class="form-control" id="alsoKnows">
? ? ? ? </div>


? ? ? ? <div class="form-group">
? ? ? ? ? <label for="power">Hero Power</label>
? ? ? ? ? <select class="form-control" id="power" required>
? ? ? ? ? ? <option *ngFor="let lang of skills" [value]="lang">{{lang}}</option>
? ? ? ? ? </select>
? ? ? ? </div>


? ? ? ? <button type="submit" class="btn btn-success">Submit</button>


? ? ? </form>
? </div>        

The forms should look something like this:

No alt text provided for this image

In the application you can see that the list of powers shows in the drop down.

In the input elements are not yet bound to the data model and hence are blank.

Binding Input elements to data

In the next step we will be implementing two-way data binding using ngModel and FormsModule that would let us bind controls in our form with the data model.

When we use the two way data binding directive [(ngModel)] Angular can track the value and user interaction of the control and keep the view synced with the model

  1. Let us go to the file hero-form.component.html
  2. go to the input tag next to the Name label
  3. Add the ngModel directive using the 2-way data binding syntax

[(ngModel)] = ".."        

Now you can see the input has been populated with the name of the developer from the list.

No alt text provided for this image

Accessing the overall form status

When we added the FormsModule in our component the Angular automatically created and attached an NGForm directive to the <form> tag in the template

To get access to the ngForm and overall form status declate a template reference variable

  1. Edit the template file hero-form.component.html
  2. <form> tag with a template reference variable #devForm and set its values as follows

<form #devForm="ngForm">        

The devForm template variable is now a reference to the ngForm directive instance that governs the form as a whole

3. run the app

4. Type something in the Name input

As you add and delete the words you can see them appear and disappear in the data model

Here is an example whatever you type in the box will be shown in the todo below

This shows that input is bound to the data

Naming control elements

When using ngModel on an element we must define a name attribute for that element.

Angular uses that assigned name to register the element with the ngFOrm directive attached to the parent form element

In this example we added the name attribute to the input element and set it to name which makes sense for the developers name

  1. Added similar ngModel bindings and name attributers to the alsoKnows and skills
  2. we can remove the diagnotic messaging that we added before
  3. To confirm that the two way data binding is working for the entire hero model add a new text binding with the json pipe at the top to the components template which serializes the data to a string

Conclusion

In this article we have learnt how to make angular forms function for a developer forms portal

Let us know what you think about the article in the comments

要查看或添加评论,请登录

Mshoppe India的更多文章

社区洞察

其他会员也浏览了