CREATE: Add New User (Reactive Forms)

In this tutorial, I will show you how to add a New User in Angular using Reactive Forms.

Importing Required Form Modules


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

ReactiveFormsModule: Enables the use of reactive forms in your component.

FormBuilder: Helps create form groups and form controls easily.

Validators: Provides built-in validation methods like required, email, etc.

These imports are essential for building and validating forms programmatically.

Component TypeScript (user-form.component.ts)

This component is responsible for creating a form, handling user input, performing validation, and submitting data.


@Component({
  selector: 'app-user-form',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterModule],
  templateUrl: './user-form.component.html'
})
export class UserFormComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private userService: UserService,
    private router: Router
  ) {}

  form = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.required],
    salary: ['', Validators.required],
  });

  ngOnInit(): void {}

  submit() {
    this.userService.addUser(this.form.value).subscribe(() => {
      this.router.navigate(['/']);
    });
  }
}

standalone: true → This component can work without being inside a module (Angular 17+ feature).

imports → Required modules for forms, routing, and common directives.

templateUrl → Points to the HTML form template.

Creating a User form in user.component.html

The form is linked to the reactive form in TypeScript using formGroup.

Each field is connected with formControlName, ensuring two-way form control management.


<h3>Add User</h3>

<form [formGroup]="form" (ngSubmit)="submit()">

  <div class="mb-3">
    <label>Name</label>
    <input type="text" class="form-control" formControlName="name">
  </div>

  <div class="mb-3">
    <label>Email</label>
    <input type="email" class="form-control" formControlName="email">
  </div>

  <div class="mb-3">
    <label>Salary</label>
    <input type="number" class="form-control" formControlName="salary">
  </div>

  <button class="btn btn-success" type="submit">Save</button>
</form>