to create the Angular form, you have to use the below step.
Step1:- Firstly import FormsModule, ReactiveFormsModule in the app.module.ts file.
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
Now, include modules into imports array.
@NgModule({ imports: [ FormsModule, ReactiveFormsModule, ] });
Step2:- Now, add HTML content in the add-employee.component.html file, which is view on the browser.
I have created a form that has three input fields like employee first name, employee last name and employee department after that created a submit button.
Note:- I have created reactive form and used formGroup to represent the form Name, formControlName used for the form field which is bind the form field value.
<div align="center" style="width:50%"> <h4>Create Employee</h4> <form [formGroup]="addEmpForm" (ngSubmit)="onEmpSubmit()" novalidate autocomplete="off"> <div class="input-item"> <input type="text" formControlName="empFirstName" placeholder="Employee First Name" class="input-bordered form-control"> </div> <div class="div-gap"></div> <div class="input-item"> <input type="text" formControlName="empLastName" placeholder="Employee Last Name" class="input-bordered form-control"> </div> <div class="div-gap"></div> <div class="input-item"> <input type="text" formControlName="empDepart" placeholder="Employee Department" class="input-bordered form-control" > </div> <div class="div-gap"></div> <div class="gaps"></div> <div class="d-flex justify-content-between align-items-center"> <button type="submit" name="emp_sub" class="sub-button">Create</button> </div> </form> </div>
Step3:- Now, css content added in the add-employee.component.scss file
.input-bordered { border-radius: 4px; border: 2px solid #d3e0f3; width: 100%; padding: 10px 15px; line-height: 20px; } .div-gap{height:20px;} .sub-button{ border-radius: 4px; background-color: blue; padding: 10px;} .invalid-feedback{color:#ff0000}
Step4:- This file is used to implement Businees logic.
FormBuilder is used to bind the form value and you can perform any action in the onEmpSubmit() function.
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-add-employee', templateUrl: './add-employee.component.html', styleUrls: ['./add-employee.component.scss'] }) export class AddEmployeeComponent implements OnInit { addEmpForm: FormGroup; constructor(private fb: FormBuilder){} ngOnInit(): void { this.addEmpForm = this.fb.group({ empFirstName: [''], empLastName: [''], empDepart: [''] }); } onEmpSubmit(){ console.log(this.addEmpForm.value); // perform an action like hit the backend API } }
Note:- Now, you can see the screen, user filled the form value and click on submit button then show value into console.