angular form in typescript

Angular provides two different ways to handle forms: template-driven forms and reactive forms. In this answer, I will cover how to create a form using reactive forms in Angular with TypeScript.

  1. Import the necessary modules in your component:
index.ts
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
69 chars
2 lines
  1. Declare a FormGroup variable to hold your form data in your component:
index.ts
myForm: FormGroup;
19 chars
2 lines
  1. Inject FormBuilder into your component constructor:
index.ts
constructor(private fb: FormBuilder) { }
41 chars
2 lines
  1. Create your form in ngOnInit method using FormBuilder. Here's an example with a simple form:
index.ts
ngOnInit() {
  this.myForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
    age: ['', Validators.required],
    gender: ['', Validators.required],
    address: this.fb.group({
      street: ['', Validators.required],
      city: ['', Validators.required],
      state: ['', Validators.required],
      zip: ['', Validators.required]
    })
  });
}
416 chars
15 lines
  1. In your component HTML, bind the formGroup directive to the FormGroup variable you created earlier:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <!-- Form controls go here -->
</form>
93 chars
4 lines
  1. Add form controls to your HTML form using the formControlName directive:
<div class="form-group">
  <label for="name">Name</label>
  <input type="text" class="form-control" formControlName="name" />
</div>

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

<!-- More form controls go here -->

<button type="submit">Submit</button>
347 chars
14 lines
  1. Implement the onSubmit method in your component to handle form submission:
index.ts
onSubmit() {
  // Do something with the form data
}
52 chars
4 lines

That's it! You now have a fully functional form in your Angular application using reactive forms and TypeScript.

gistlibby LogSnag