Angular 6 : Submit model base Form

Angular 6 : Submit model base Form 



Here is the example to submit model base form in angular 6

 

app.module


import { FormsModule } from "@angular/forms";
 imports: [
   ...
    FormsModule ,
    ...
  ]

Model

export class Employee {
    EmployeeID : number;
    FullName : string;
    EmpCode : string;
    Mobile : string;
    Position : string;
}

Component

export class EmployeeComponent implements OnInit {
  formData : Employee;
  constructor() { 
    this.formData = {
      EmployeeID : null,
      FullName : '',
      EmpCode: '',
      Position: '',
      Mobile: ''
    }
   }
  ngOnInit() {
  }
  submitform() : void{
    console.log("FullName = " + this.formData.FullName)
    console.log("EmpCode = " + this.formData.EmpCode)
    console.log("Position = " + this.formData.Position)
    console.log("Mobile = " + this.formData.Mobile)
    //TODO
    //Call service to insert data
  }
}

HTML

<form #form="ngForm" (submit)="onSubmit(form)" autocomplete="off">
  <div class="form-group">
    <label>Fullname</label>
    <input name="FullName" #FullName="ngModel" [(ngModel)] = "formData.FullName" class="form-control" required>
    <div class="validation-error" *ngIf="FullName.invalid && FullName.touched">Fullname is required</div>
  </div>
  <div class="form-group">
    <label>Position</label>
    <input name="Position" #Position="ngModel" [(ngModel)] = "formData.Position" class="form-control">
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label>EmpCode</label>
      <input name="EmpCode" #EmpCode="ngModel" [(ngModel)] = "formData.EmpCode" class="form-control">
    </div>
    <div class="form-group col-md-6">
      <label>Mobile</label>
      <input name="Mobile" #Mobile="ngModel" [(ngModel)] = "formData.Mobile" class="form-control">
    </div>    
  </div>
  <div class="form-group"> 
    <button type="button" [disabled]="form.invalid" (click) = "submitform()" class="btn btn-lg btn-block">
      Submit Button
    </button>
  </div>
</form>

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment