Angular Forms

There are two ways to work with forms template driven forms and model driven forms.

Here we will see how use model driven forms, since its widely used in smaller and bigger projects. It is robust and highly scalable and re-usable. Model driven forms are nothing but reactive forms.

Lets create a login component using below command
Ng g component login
Below screenshot shows the output of the command.

component-login

To utilize model driven forms, we need to import reactive form module in app.module.ts as below.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MyfirstcomponentComponent } from './myfirstcomponent/myfirstcomponent.component';
import { CustomDirective } from './custom.directive';
import { SquarePipe } from './square.pipe';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import {CommonService } from './common.service';
import { HttpClientModule } from '@angular/common/http';
import { LoginComponent } from './login/login.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    MyfirstcomponentComponent,
    CustomDirective,
    SquarePipe,
    HomeComponent,
    ContactComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  providers: [CommonService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Login.component.ts

We can see from below code, loginForm is initialized with form group, and emailid and passwd initialized with default values as form controls. In model driven forms each input or form element is initiated as a form control. And form control will always be associated with the form group.

import { Component, OnInit } from '@angular/core';
import {CommonService} from '../common.service';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: any;
  constructor(private cs : CommonService) { }

  ngOnInit(): void {
    this.loginForm = new FormGroup({ 
      emailid: new FormControl("name@gmail.com"),
      passwd: new FormControl("qwerty") 
   }); 
  }

  onSubmit(data) {
    alert('You have logged in successfully - ', data.emailid);
  }

}

Login.component.html
<div> 
   <form [formGroup] = "loginForm" (ngSubmit) = "onSubmit(loginForm.value)" > 
       <input type = "text"  name = "emailid" placeholder = "emailid" 
          formControlName = "emailid">
       <br/> 
       
       <input type = "password"  name = "passwd" 
          placeholder = "passwd" formControlName = "passwd" >
      <br/ >
       
       <input type = "submit"  value = "Log In" >
    </form>
 </div> 

We used formGroup for the form in the.html file in square bracket; for example, [formGroup] = “LoginForm.” The function onSubmit, for which loginForm.value is passed, is called upon submit.

Uses the formControlName input tag. A value is given which we used in the file login.component.ts.

The control will pass to the onClickSubmit function, which is defined in the login.component.ts file, when you click Send.

Below screenshot shows the output on the browser

onclicksubmit-output

Form Validation:

Angular Forms have its own inbuild validation technique. We need to import validators fom angular forms.

import { FormGroup, FormControl, Validators } from '@angular/forms';

Angular has built-in validators such as mandatory field, minlength, maxlength, and pattern

This is how we use validators for mandatory and check for minimum length.below code is part of login.component.ts

this.loginForm = new FormGroup({ 
      emailid: new FormControl("name@gmail.com",[Validators.required,Validators.minLength(5)]),
      passwd: new FormControl("qwerty",Validators.required) 
   }); 

Lets make the submit disable until the data in form is valid. Using below code in html, we can make the submit button disabled. Submit button will be enabled only when all the validators are passed or satisfied.

<input type = "submit" [disabled] = "!loginForm.valid" value = "Log In">
Below screenshot shows the output on the browser

form-validation

Custom form validation

We can also perform our custom validation. Lets check the password length is above 5 .

we have created a function checkPwd and the same is used in the formcontrol – passwd: new FormControl(“”, this.checkPwd).

If the characters are less than five, it will return with the passwd true as shown above – return {“passwd” : true};. If the characters are more than five, it will consider it as valid and the login will be enabled.

  ngOnInit(): void {
    this.loginForm = new FormGroup({ 
      emailid: new FormControl("name@gmail.com",[Validators.required,Validators.minLength(5)]),
      passwd: new FormControl("qwerty",this.checkPwd) 
   }); 
  }

  checkPwd(fc: { value: string | any[]; }){
    if(fc.value.length <=5 ){
      return {"passwd" : true};
    }
  }

Subscribe Now