Home >>Angular 6 Tutorial >Angular 6 Forms
We'll see how forms are used in Angular 6 in this part. We 're going to explore two methods of dealing with forms-prototype based form and model driven forms.
Most of the work is done in the prototype with a template guided form and most of the work is done in the object class with the layout drived form.
Let's start focusing on the driven template form now. We'll build a quick login form, add the email id, password and send the account button. To begin with, we will import from @angular/core to FormsModule that is done as follows in app.module.ts –
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path: 'new-cmp',component: NewCmpComponent}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
So we imported the FormsModule in app.module.ts and the same is included in the array of imports as seen in the highlighted code.
Let's create our form now in the app.component.html file.
<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >
<input type = "text" name = "eid" placeholder = "eid" ngModel>
<br/>
<input type = "password" name = "pswd" placeholder = "passwd" ngModel>
<br/>
<input type = "submit" value = "submit">
</form>
We built a basic form with email id, password and the submit button for input tags. We assigned it to type, name, and placeholder.
We need to build model form controls in template driven forms by inserting the ngModel directive and the name attribute. So anywhere we want Angular to access our data from the sources, add ngModel as seen above to the name. Now, if we need to read the emailid and passwd, then we need to connect the ngModel through it.
If you see, we applied the ngForm to the # userlogin, too. You need to apply the ngForm directive to the form template that we developed. We've also introduced onClickSubmit feature and allocated userlogin.value to it.
Let's build the feature in the app.component.ts now, and get the values in the form entered.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
constructor(private myservice: MyserviceService) { }
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
}
onClickSubmit(data) {
alert("Entered Email id : " + data.emailid);
}
}
We have defined the function onClickSubmit in the app.component.ts file above. Clicking on the submit form button will result in the check coming to the function above.
The form looks just as seen below. Let us enter the data in it, and the email I d is already entered in the submit feature.
We have to import the ReactiveFormsModule from @angular / forms in the model guided form, and use the same in the import array.
A transition is going on in app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyserviceService } from './myservice.service';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
HttpModule,
ReactiveFormsModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
We need to import a few modules for the model driven form at app.component.ts. For eg, from '@angular/forms' import { FormGroup, FormControl }.
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
constructor(private myservice: MyserviceService) { }
ngOnInit() {
this.todaydate = this.myservice.showTodayDate();
this.formdata = new FormGroup({
emailid: new FormControl("phptpoint@gmail.com"),
passwd: new FormControl("xyz654")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
At the beginning of the class the variable formdata is initialized, and the same is initialized with FormGroup as seen above. The emailid and passwd variables are configured with default values to display in the form. You should keep it blank if you like.
We also used formdata to configure the form values; in the form UI app.component.html, we will do the same.
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "eid" placeholder = "Enter your Email"
formControlName="emailid">
<br/>
<input type = "password" class = "fortextbox" name="paswd"
placeholder = "Enter your password" formControlName = "passwd">
<br/>
<input type = "submit" class = "forsubmit" value = "Log In">
</form>
</div>
<p>
Email: {{emailid}}
</p>
We used formGroup for the form in the.html file in square bracket; for example, [formGroup]="formdata. The feature onClickSubmit, for which formdata.value is passed, is called mostly on submission.
Uses the formControlName input tag. A value is given which we used in the file app.component.ts.
The control must pass to the onClickSubmit feature, which is specified in the app.component.ts file, when you click Send.
Let's discuss validation of the form now using model driven form. You can either use the built-in validation form, or use the custom validation approach. In the manner we shall use all approaches. The same instance we created in one of our previous sections will proceed. We need to import validators from @angular / forms with Angular 4 as shown below −
import { FormGroup, FormControl, Validators} from '@angular/forms'
Angular has integrated validators like mandatory field, minlength, maxlength, and pattern. Those are to be accessed through the module Validators.
You may simply add validators or an array of validators required to say Angular if a specific field is compulsory.
Let's seek the same on one of the textboxes entry, that is, email address. We applied the following validation parameters for the e-mail I d −
Required
Pattern Matching
This is how a file in app.component.ts undergoes validation.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("")
});
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
In Validators.compose, you should add the list of things in the input field you want to verify. Right now, we've added the required parameters and pattern matching to take only valid email.
The send button is disabled in the app.component.html if all of the inputs to the form are not valid. It functions as follows −
<div>
<form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" >
<input type = "text" class = "fortextbox" name = "eid" placeholder = "Enter your Email"
formControlName = "emailid">
<br/>
<input type = "password" class = "fortextbox" name = "pswd"
placeholder = "Enter your password" formControlName = "passwd">
<br/>
<input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit"
value = "Log In">
</form>
</div>
<p>
Email: {{emailid}}
</p>
We've added disabled in the square bracket for the submit button, which is given value-! The formdata.valid . Thus, if the formdata.valid is not valid, the button remains disabled and the user can not submit it.
The email Id entered in the above case is invalid and therefore the login button is disabled. Let's try to enter the correct email Id now, and see the difference.
Now, the inserted email Id is valid. So we can see that the login button is enabled, and the user can submit it. The email Id entered with this is seen at the bottom.
Let's now seek the same method on custom validation. We may describe our own custom feature for custom validation, and attach the necessary information to it. We are going to see an explanation for the same now.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 6 Project!';
todaydate;
componentproperty;
emailid;
formdata;
ngOnInit() {
this.formdata = new FormGroup({
emailid: new FormControl("", Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^ @]*")
])),
passwd: new FormControl("", this.passwordvalidation)
});
}
passwordvalidation(formcontrol) {
if (formcontrol.value.length < 5) {
return {"passwd" : true};
}
}
onClickSubmit(data) {this.emailid = data.emailid;}
}
Throughout the illustration above, we built a password validation feature and the same is used throughout the formcontrol − passwd: new FormControl(‘', this.passwordvalidation) in a previous segment.
We'll check in the feature we've created if the length of the characters entered is sufficient. If the characters are less than five, then the password correct must return as seen above-return {"passwd": true}; If there are more than five characters, it will be considered valid, and the login will be enabled.
Just three characters are decided to enter in the login, and the authentication is disabled. We need more than five characters to allow login. Let's insert and check a correct character length now.
The login is allowed if both the password and the email Id are valid. The email will display up at the bottom when we sign in.