Angular 2 FormGroup Recative form Example


Angular 2 FormGroup  Recative form Example
https://www.concretepage.com/angular-2/angular-2-formgroup-example#set-get


FormControl:  It is a class that tracks the value and validation state of a form control.
FormGroup:    It is a class that tracks the value and validity state of a group of FormControl.
FormArray:    It is a class that tracks the value and validity state of array of FormControl, FormGroup and FormArray.
FormControlName:  It is a directive that syncs a FormControl in an existing FormGroup to a form control by name.
FormGroupDirective: It is a directive that binds an existing FormGroup to a DOM element.
FormGroupName:  It is a directive that syncs a nested FormGroup to a DOM element.
FormArrayName:   It is a directive that syncs a nested FormArray to a DOM element.



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

  constructor(private formBuilder: FormBuilder) { }
contactForm: FormGroup;

  ngOnInit() {
    this.createForm();
  }
  /* start form code */
  private createForm() {

    this.contactForm = this.formBuilder.group({
      contact_type_name: new FormControl('', {
        validators: [Validators.required, Validators.maxLength(55)],
        updateOn: 'change'
      }),
    });
  }
  getError() {
    return '*This is required field'
  }
  /**  submit function  */

  onSubmit() {
    if (this.contactForm.valid) {
      this.settingService.postContactType(this.contactForm.value).subscribe(
        data => this.closeDialog(data),
        error => this.closeDialog(error)
      )
    }  this.contactForm.reset();
  }
  
  closeDialog(data) {
    this.dialogRef.close(data);
  }
}



-----------------html--------------------------------------

<h1 mat-dialog-title>
  New dumy form</h1>
<form [formGroup]="contactForm" novalidate>
  <mat-form-field class="width_100">
    <input matInput placeholder=" Enter New ContactType" formControlName="contact_type_name" required>
    <mat-error *ngIf="contactForm['controls'].contact_type_name.invalid">{{getError()}}</mat-error>

  </mat-form-field>
  <mat-dialog-actions class="float_right form_buttons">
    <button mat-raised-button (click)="closeDialog('cancle')" class="uppercase_button cancel_btn">Cancel</button>
    <button mat-raised-button type="submit" [disabled]="!contactForm.valid" (click)="onSubmit()" class="uppercase_button save_btn">Save</button>
  </mat-dialog-actions>
</form>


Comments

Popular Posts