Others

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';
 
@Component({
  selector: 'app-reviews',
  templateUrl: './reviews.component.html',
  styleUrls: ['./reviews.component.css']
})
export class ReviewsComponent implements OnInit {
  reviewForm:any;
courses:string[]=["Java","HTML","CSS3","Angular","React JS"];
 constructor(private formbuilder:FormBuilder,private rs:ReviewService) { 
    this.reviewForm=this.formbuilder.group({
      name:['',[Validators.required,isSymbols]],
      message:['',Validators.required],
      email:['',[Validators.required, Validators.pattern(
        "^[A-Za-z][A-Za-z_\.0-9]+@[A-Za-z]+[\.][A-Za-z]{2,5}$")]],
        
      course:['Java']
    });
  }
 
  ngOnInit() {
  }
  
  saveReview(){
    var temp:any={
      name: this.reviewForm.value.name,
      email: this.reviewForm.value.email,
      course:this.reviewForm.value.course,
      message:this.reviewForm.value.message,
      reviewdate:new Date().toString()
    }
    this.rs.postReviews(temp).subscribe(
      data=>{
        alert('Your review is saved')
        location.reload();
      },
      (error)=>alert('Not saved ---some Error')
    )
 
  }
}
 
 
function isSymbols(input: FormControl){
  let temp:RegExp=new RegExp('[\._$@0-9]');
  let temp1:boolean=false;
  if(!temp.test(input.value))
      temp1=true;
 
    return temp1?null:{needFormat:true};
}
 



Place the template form like below


Full template of screen as
<div class="rform">
  <form      [formGroup]="reviewForm"  (submit)="saveReview()">
         <table>
             <tr>
             <th>Name</th>
             <td><input type="text" formControlName="name"></td>
             <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>
             </tr>
              <tr>
             <th>Email</th>
             <td><input type="text" formControlName="email"></td>
             <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>
             </tr>
             <tr>
             <th>Course</th>
             <td><select formControlName="course">
                 <option *ngFor="let x of courses">{{x}}</option>
                </select>
                </td>
             <td></td>
             </tr>
             <tr>
                 <th>Message</th>
                 <td><textarea rows=6 cols=50 formControlName="message">
                     </textarea></td>
                 <td>
                        <div *ngIf='reviewForm.controls.message.hasError("required")'>
                                Should be filled</div>
                 </td>
             </tr>
             <tr><td colspan="3" align="center">
                    <button type="submit"  class="btn btn-primary" [disabled]="!reviewForm.valid">
                               Post Review</button>
                </td></tr>
         </table>
   
   
    </form>
</div>


Now the output will look like




Day 1
Day 2
Day 3
Day 4

No comments:

Post a Comment