Git Tutorial

Reactive Forms – Using FormBuilder

Import ReactiveFormsModule

In the component, you need to import ReactiveFormsModule directly inside the @Component decorator. This is how you handle form functionality in Angular without a module.

Here’s how you can modify the reactive-form.component.ts:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';

@Component({
selector: 'app-reactive-form',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent {
myForm: FormGroup;

constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
firstName: [''],
lastName: [''],
email: ['']
});
}

onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
} else {
console.log('Form is invalid');
}
}
}

Create the Template

Next, create the template for your form in reactive-form.component.html. Here’s an example:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div>
<label for="firstName">First Name:</label>
<input id="firstName" formControlName="firstName" type="text" />
</div>

<div>
<label for="lastName">Last Name:</label>
<input id="lastName" formControlName="lastName" type="text" />
</div>

<div>
<label for="email">Email:</label>
<input id="email" formControlName="email" type="email" />
</div>

<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

Add the Component to Your App

In the app.component.ts or any other component where you want to use this form, import the ReactiveFormComponent directly:

import { Component } from '@angular/core';
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';

@Component({
selector: 'app-root',
template: `<app-reactive-form></app-reactive-form>`,
})
export class AppComponent {}

Style the Form (Optional)

You can add basic CSS for better presentation in the reactive-form.component.css:

form {
display: flex;
flex-direction: column;
gap: 10px;
width: 300px;
margin: 0 auto;
}

input {
padding: 8px;
font-size: 14px;
}

button {
padding: 10px;
font-size: 16px;
cursor: pointer;
}

Summary

This is how you can create a simple reactive form using FormBuilder in a standalone component. The key points are:

  1. Import ReactiveFormsModule in the imports array inside the standalone component.
  2. Use FormBuilder to define your form group and form controls.
  3. Bind the form to the template using [formGroup] and form control names with formControlName.
  4. Handle form submission and validation.

This is a simple example, and you can extend this by adding form validation and more advanced features like FormArray or FormControl for more complex forms.

1 thought on “Reactive Forms – Using FormBuilder”

  1. Pingback: What Is Angular - Tech Mentor

Leave a Comment

Your email address will not be published. Required fields are marked *