Angular Forms for beginners
2 min readAug 18, 2023
Angular provide forms to enable users to log in , update profile and to perform many tasks.
Prerequisites
- Install nodejs@13.0.0 & it will install npm@8.1.2
- npm install -g @angular/cli@13.0.0
what are types of forms?
- Template-driven Form — Basic form , Rely on directives in the template to create and manipulate the model. Simple form to an app , such as sing up form. If you have very basic requirements and logic then template driven forms could be a good fit
- Reactive Form — Advanced Form , Provide direct and explicit access to the form’s object model. Reactive forms are more robust , more scalable and testable.
Setup in template-driven forms
<input type="text" [(ngModel)="userName">
export class UserComponent{
userName = '';
}
Setup in Reactive forms
// Declare ReactiveModule in Module.ts
import { ReactiveFormsModule } from '@angular/forms'
// Add FormGroup and Formcontrolname in Template
<form [formGroup]="loginForm " name="login">
<input type="text" formControlName="username" placeholder="Name" />
</form>
// Declare formGroup and FormControl in Component
loginForm = new FormGroup({
email: new FormControl(""),
password: new FormControl("")
})
// Get Form Value in Component
this.loginForm.get('email')?.value
// Add Reactive form validation
<input type="email" formControlName="email" placeholder="Email" required />
// Add Validators in the form
loginForm = new FormGroup({
email: new FormControl("",Validators.required),
password: new FormControl("", Validators.required)
})