Friday, 20 July 2018

Angular 4 Tutorial - Day 4

Day 1
Day 2
Day 3
Day 4

Today it will cover as form handling in angular.

1.       Template based approach – ngModel
2.       Model driven approach – form builder

Create new services as enquiry service.

Import it and register it to app.modules.ts like  other services like

Calling the post method to send the data from services to WebApi.

Template based approach

Create an enquiry form on right body which will display the enquiry form, create component as:

Now you should have the enquiry in rightbody component as below.

Place below code for creating the form for enquiry for as: enquiry.component.html

You will get output as below after placing the templpates as:

Now the concept is when we are going to save from it will show the loading icons and once it is success will give the message that data save successfully

Now lets have validation for forms;
You can do check in enquiry.component.ts page.

And method as sendenquery method which will call on the button click

Now when you are clicking the button without entering data it will shows you error as

Calling the service as else part as like below,

Now just perform for sending the form data

Once message send success you will get the below message and than back to enquiry form.

Model Based Approach

For from based approach you work than you need to add recative form module in app.module.ts as like;

Register it into module sections

Need to import the below modules
§  FormBuilder
§  Validator
§  Form Control

Now in Constructor you need to inject the formbuilder and review Services
Formbuilder use to construct the input elements  and service where we will perform the inputs.

Now if you see the above code there is

This.reviewform = this.formbuilder.group({})

It will use to group the list on name, message, email, course input controls.

Name : [‘ ‘ ,[validatior.required, isSymbol]]

First value ‘’ is for default value,
Second values is an array at form of validation. Validator.required : for required filed and Issymbol is for custom validatior. Which can be outside of class as like below.

Full code for reviews.component.ts as
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormControl } from '@angular/forms';
import { ReviewService } from '../../services/review.service';
  selector: 'app-reviews',
  templateUrl: './reviews.component.html',
  styleUrls: ['./reviews.component.css']
export class ReviewsComponent implements OnInit {
courses:string[]=["Java","HTML","CSS3","Angular","React JS"];
 constructor(private formbuilder:FormBuilder,private rs:ReviewService) { 
      email:['',[Validators.required, Validators.pattern(
  ngOnInit() {
    var temp:any={
      name: this.reviewForm.value.name,
      email: this.reviewForm.value.email,
      reviewdate:new Date().toString()
        alert('Your review is saved')
      (error)=>alert('Not saved ---some Error')
function isSymbols(input: FormControl){
  let temp:RegExp=new RegExp('[\._$@0-9]');
  let temp1:boolean=false;
    return temp1?null:{needFormat:true};

Place the template form like below

Full template of screen as
<div class="rform">
  <form      [formGroup]="reviewForm"  (submit)="saveReview()">
             <td><input type="text" formControlName="name"></td>
                    <div *ngIf='reviewForm.controls.name.hasError("required")'>
                            Should be filled</div>
                 <div *ngIf='reviewForm.controls.name.hasError("needFormat")'>
                                No Symbols allowed for name</div>
             <td><input type="text" formControlName="email"></td>
                    <div *ngIf='reviewForm.controls.email.hasError("required")'>
                            Should be filled</div>
                    <div *ngIf='reviewForm.controls.email.hasError("pattern")'>
                                Should be in email format</div>
             <td><select formControlName="course">
                 <option *ngFor="let x of courses">{{x}}</option>
                 <td><textarea rows=6 cols=50 formControlName="message">
                        <div *ngIf='reviewForm.controls.message.hasError("required")'>
                                Should be filled</div>
             <tr><td colspan="3" align="center">
                    <button type="submit"  class="btn btn-primary" [disabled]="!reviewForm.valid">
                               Post Review</button>

Now the output will look like

Day 1
Day 2
Day 3
Day 4

No comments:

Post a Comment