7.B. Model Driven Forms or Reactive Forms
Create an employee registration form as a reactive form.
In Angular, you can create an employee registration form using either Model-Driven Forms (also known as Reactive Forms) or Template-Driven Forms. Below, I'll demonstrate how to create an employee registration form as a Reactive Form.
Reactive Forms provide more control and flexibility in handling form data and validations. To create an employee registration form using Reactive Forms, follow these steps:
Set Up Your Angular Project:
If you haven't already set up an Angular project, you can do so by using Angular CLI:
Design the HTML Form:
Open the employee-registration.component.html file and design your form. Here's a simple example:
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()"> <div> <label for="name">Name:</label> <input type="text" id="name" formControlName="name" /> </div> <div> <label for="email">Email:</label> <input type="email" id="email" formControlName="email" /> </div> <div> <label for="department">Department:</label> <input type="text" id="department" formControlName="department" /> </div> <button type="submit">Submit</button> </form>
Create a FormGroup:
In the employee-registration.component.ts file, import the necessary modules and create a FormGroup with FormControl instances for each input field. Add any necessary validators.
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-employee-registration', templateUrl: './employee-registration.component.html', styleUrls: ['./employee-registration.component.css'] }) export class EmployeeRegistrationComponent implements OnInit { employeeForm!: FormGroup; // ✅ FIXED constructor(private fb: FormBuilder) {} ngOnInit(): void { this.employeeForm = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], // Add other fields here... }); } onSubmit(): void { console.log(this.employeeForm.value); } }
Add the ReactiveFormsModule:
In your app.module.ts file, make sure to import the ReactiveFormsModule and add it to the imports array of the @NgModule decorator:
import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ // ... ], imports: [ BrowserModule, ReactiveFormsModule, // Add this line ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Comments
Post a Comment