Friday, 23 November 2018

Forms in Angular


There are 2 ways to create forms in Angular 

Template Driven Forms

1).Template Driven Forms are created  completely in HTML.
2).easy to build and understand.
3).great for creating simple forms
4).creating complex forms using template driven approach is not recommended
    as the HTML can get very complicated and messy
5).not easy to unit test template forms as the logic is in the HTML.


Reactive Forms (Also called Model Driven Forms)

1).allow us to build the form completely in code.
2).more flexible and has many benefits over template forms.
3).easy to add form input elements dynamically and adjust validation at run-time based on the decisions made in code.
4).easy to unit test as most of the logic and validation is in the component class.
5). only downside of reactive forms is that they require more code than template forms.

Note:- Two classes that we commonly use to create a form control tree is 
1).FormGroup and
2).FormControl.
which creates a form with a group of controls,

Note:- 
error :- Can't bind to 'formGroup' since it isn't a known property of 'form' 
solution:- formGroup and formControlName) are in ReactiveForms module, 
                 import { ReactiveFormsModule } from '@angular/forms'; your module.
 Reference From
=======================Example.ts================================
import { Component, OnInit } from '@angular/core';
// Import FormGroup and FormControl classes
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-create-employee',
  templateUrl: './create-employee.component.html',
  styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
  // This FormGroup contains fullName and Email form controls
  employeeForm: FormGroup;

  constructor() { }

  // Initialise the FormGroup with the 2 FormControls we need.
  // ngOnInit ensures the FormGroup and it's form controls are
  // created when the component is initialised
  ngOnInit() {
    this.employeeForm = new FormGroup({
      fullName: new FormControl(),
      email: new FormControl()
    });
  }
  onSubmit(): void {
     console.log(this.employeeForm.value);
  }
}
//Both FormControl and FormGroup classes inherit from AbstractControl class.
==========================Example.html===============================  
<form class="form-horizontal" [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
          <label class="col-sm-2 control-label" for="fullName">Full Name</label>
          <input id="fullName" type="text" class="form-control"formControlName="fullName">
          <label class="col-sm-2 control-label" for="email">Email</label>
          <input id="email" type="text" class="form-control" formControlName="email">
 </form>
                                                                                                            
2). FormBuilder   :- import { FormBuilder } from '@angular/forms';

"FormBuilder class provides syntactic sugar that shortens creating instances     of  FormControlFormGroup, or FormArray." 

-FormBuilder class is provided as a service, so first let's import the service.

The FormBuilder service has three methods:  
  • control() - Construct a new FormControl instance
  • group() - Construct a new FormGroup instance
  • array() - Construct a new FormArray instance
  =======================Example.ts using FormBuilder =========================
import { Component, OnInit } from '@angular/core';
// Import FormGroup and FormControl classes
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-create-employee',
  templateUrl: './create-employee.component.html',
  styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
    employeeForm: FormGroup;

  constructor(private fb: FormBuilder) { 
     this.employeeForm = this.fb.group({
      fullName: [''],
      email: [''],
      skills: this.fb.group({
      skillName: [''],
      experienceInYears: [''],
      proficiency: ['beginner']
  }),
});
  onSubmit(): void {
     console.log(this.employeeForm.value);
  }
}                                 

No comments:

Post a Comment

SQL STUFF Function and Get common grid data with pagination, filteration, sorting by sp & functions

========================================================================= STUFF FUNCTION ===================================================...