Skip to content

Instantly share code, notes, and snippets.

@rlunaro
Last active November 16, 2022 16:20
Show Gist options
  • Save rlunaro/18e0a1e533530631c5118ba01c0e7698 to your computer and use it in GitHub Desktop.
Save rlunaro/18e0a1e533530631c5118ba01c0e7698 to your computer and use it in GitHub Desktop.
Notes on Reactive Forms

Configure the application to support reactive forms

In the app.module.ts, in the imports section, declare the class ReactiveFormsModule:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the component, create a property of type FormGroup

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  genders = ['male', 'female'];
  signupForm : FormGroup;

}

And initialize it:

ngOnInit() {
this.signupForm = new FormGroup( { 
  "username": new FormControl( null ), 
  "email" : new FormControl( null ), 
  "gender" : new FormControl( 'male' )
} );
}

And link it with the real form in the template:

<form [formGroup]="signupForm">

And link everyone of the controls of the form of the template with the form controls:

<input
type="text"
id="email"
formControlName="email"
class="form-control">

Adding validators

Validators can be added in the second parameter of the creation. For instance, Validators.required adds a validator that requires that this field is required:

  "username": new FormControl( null, Validators.required ), 
  "email" : new FormControl( null, [Validators.required, 
                                    Validators.email ] ), 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment