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:
Scaffolding the App
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:
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.
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
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:
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 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:
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
[(ngModel)] = ".."
Now you can see the input has been populated with the name of the developer from the list.
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
<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
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