Angular forms are used to handle user input, validation, and form data management in web applications. Angular provides two main types of forms: template-driven and reactive forms. Below are 20 questions with detailed answers, examples, and implementation steps related to Angular forms.
1. What are the two types of forms in Angular? How do they differ?
Answer:
- Template-Driven Forms:
- Simpler to set up, ideal for small forms.
- Form structure and logic are defined in the HTML template.
- Uses directives like
ngModelfor two-way data binding.
- Reactive Forms:
- Highly scalable and testable, suitable for complex forms.
- Form structure and logic are defined in the TypeScript class.
- Uses
FormControlandFormGroupfor managing form state.
Example:
Template-Driven Form:
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"> <input type="text" name="username" ngModel required /> <button type="submit">Submit</button> </form>
Reactive Form:
this.userForm = new FormGroup({
username: new FormControl('', Validators.required)
});
2. How do you create a template-driven form in Angular?
Steps to Implement:
- Import
FormsModulein yourAppModule. - Define the form in your HTML using the
ngFormdirective. - Use
ngModelfor two-way data binding. - Handle the form submission using the
(ngSubmit)event.
Example:
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"> <label for="email">Email:</label> <input type="email" id="email" name="email" ngModel required /> <button type="submit">Submit</button> </form>
3. How do you create a reactive form in Angular?
Steps to Implement:
- Import
ReactiveFormsModulein yourAppModule. - Define a
FormGroupandFormControlin your component. - Bind the
formGroupdirective to the form in your HTML. - Use the
formControlNamedirective to bind controls.
Example:
Component:
import { FormGroup, FormControl, Validators } from '@angular/forms';
this.loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', Validators.required)
});
Template:
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()"> <input type="email" formControlName="email" placeholder="Email" /> <input type="password" formControlName="password" placeholder="Password" /> <button type="submit">Login</button> </form>
4. How do you validate template-driven forms?
Answer:
Validation in template-driven forms is achieved using Angular’s built-in validators like required, minlength, and maxlength.
Steps to Implement:
- Add validation attributes to form controls in the template.
- Use
ngModelto track control state. - Display validation error messages based on control status.
Example:
<form #userForm="ngForm">
<input type="text" name="username" ngModel required minlength="3" #username="ngModel" />
<div *ngIf="username.invalid && username.touched">
<small *ngIf="username.errors?.required">Username is required.</small>
<small *ngIf="username.errors?.minlength">Username must be at least 3 characters.</small>
</div>
</form>
5. How do you validate reactive forms?
Answer:
Reactive forms use Validators to perform validation.
Steps to Implement:
- Define validators in the
FormControlsetup. - Access validation errors using
control.errors. - Display error messages in the template.
Example:
Component:
this.registerForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(6)])
});
Template:
<div *ngIf="registerForm.controls['email'].invalid && registerForm.controls['email'].touched"> <small *ngIf="registerForm.controls['email'].errors?.required">Email is required.</small> <small *ngIf="registerForm.controls['email'].errors?.email">Invalid email format.</small> </div>
6. What are custom validators in Angular?
Answer:
Custom validators are user-defined functions that validate form controls based on specific business logic.
Steps to Implement:
- Create a validator function that returns an error object or
null. - Use the validator in a
FormControl.
Example:
function passwordStrength(control: FormControl): ValidationErrors | null {
const value = control.value || '';
if (!value.match(/[A-Z]/) || !value.match(/[0-9]/)) {
return { passwordStrength: 'Password must include an uppercase letter and a number.' };
}
return null;
}
this.registerForm = new FormGroup({
password: new FormControl('', [Validators.required, passwordStrength])
});
7. How do you handle dynamic forms in Angular?
Answer:
Dynamic forms allow you to create form controls dynamically at runtime.
Steps to Implement:
- Use
FormArrayto manage dynamic controls. - Add or remove controls using
FormArraymethods.
Example:
Component:
this.skillsForm = new FormGroup({
skills: new FormArray([])
});
addSkill() {
(this.skillsForm.get('skills') as FormArray).push(new FormControl(''));
}
removeSkill(index: number) {
(this.skillsForm.get('skills') as FormArray).removeAt(index);
}
Template:
<div formArrayName="skills">
<div *ngFor="let skill of skillsForm.controls['skills'].controls; let i = index">
<input [formControlName]="i" placeholder="Skill {{ i + 1 }}" />
<button (click)="removeSkill(i)">Remove</button>
</div>
</div>
<button (click)="addSkill()">Add Skill</button>
8. What is FormBuilder, and how is it used?
Answer:
FormBuilder is a service in Angular that simplifies the creation of form groups and controls.
Steps to Implement:
- Import
FormBuilderfrom@angular/forms. - Use the
groupmethod to define aFormGroup.
Example:
constructor(private fb: FormBuilder) {}
this.contactForm = this.fb.group({
name: ['', Validators.required],
email: ['', Validators.email]
});
9. What is the role of ngModel in template-driven forms?
Answer:
The ngModel directive enables two-way data binding between form controls and the component class. It synchronizes the input’s value with the component’s data.
Example:
<input type="text" name="username" [(ngModel)]="username" />
<p>Username: {{ username }}</p>
10. How do you reset a form in Angular?
Answer:
Forms can be reset using the reset method for both template-driven and reactive forms.
Example:
Template-Driven Form:
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)"> <input type="text" name="username" ngModel /> <button type="button" (click)="userForm.reset()">Reset</button> </form>
Reactive Form:
this.userForm.reset();