Form Control and Validation


Form Control and Validation Interview with follow-up questions

1. What is form control in Angular?

A form control is an object (FormControl, an AbstractControl) that represents a single form field and tracks three things: its value, its validation status (valid/invalid/errors), and its interaction state (touched/dirty).

email = new FormControl('', [Validators.required, Validators.email]);
// email.value, email.valid, email.errors, email.touched

In reactive forms you create controls explicitly and bind them with formControlName/[formControl]; in template-driven forms ngModel creates a FormControl for you under the hood. Either way, the control is the unit Angular validates and whose state drives error display and styling.

A current note: controls are strictly typed since v14, and Angular's new signal-based forms expose a control's value and state as signals, so you'll increasingly read control state reactively rather than through observables.

↑ Back to top

Follow-up 1

How do you create a form control instance?

To create a form control instance in Angular, you can use the FormControl class from the @angular/forms module. Here's an example:

import { FormControl } from '@angular/forms';

const myFormControl = new FormControl();

Follow-up 2

What are the key properties of a form control?

A form control in Angular has several key properties:

  • value: The current value of the form control.
  • valid: A boolean indicating whether the form control is currently valid.
  • invalid: A boolean indicating whether the form control is currently invalid.
  • touched: A boolean indicating whether the form control has been touched by the user.
  • untouched: A boolean indicating whether the form control has not been touched by the user.
  • dirty: A boolean indicating whether the form control's value has changed.
  • pristine: A boolean indicating whether the form control's value has not changed.
  • errors: An object containing any validation errors for the form control.

Follow-up 3

How do you set value in form control?

To set a value in a form control in Angular, you can use the setValue() method of the form control instance. Here's an example:

myFormControl.setValue('example value');

Follow-up 4

How do you reset a form control?

To reset a form control in Angular, you can use the reset() method of the form control instance. Here's an example:

myFormControl.reset();

2. What is form validation in Angular?

Form validation is enforcing rules on user input — required fields, formats, ranges — and surfacing errors before the data is submitted. Angular runs validator functions against each control and exposes the result via valid/invalid and an errors object.

  • Built-in validators: Validators.required, email, minLength, maxLength, min, max, pattern.
  • Custom validators: a function returning null (valid) or { errorKey: … } (invalid); attach at the control or group level (group-level for cross-field rules like "passwords match").
  • Async validators: return an Observable/Promise of errors — e.g. server-side "is this username taken?" — during which status is PENDING.
new FormControl('', { validators: [Validators.required], asyncValidators: [uniqueEmail()] });

The practical points to mention: display messages based on errors plus touched/dirty so you don't nag users prematurely, and remember client-side validation is UX, not security — always validate on the server too. (Signal-based forms keep the same validator model with a signal-native API.)

↑ Back to top

Follow-up 1

What are the built-in validators in Angular?

Angular provides a set of built-in validators that can be used to validate form inputs. Some of the commonly used built-in validators in Angular are:

  • required: Validates that the input is not empty.
  • minLength: Validates that the input has a minimum length.
  • maxLength: Validates that the input has a maximum length.
  • pattern: Validates the input against a regular expression.
  • email: Validates that the input is a valid email address.
  • min: Validates that the input is greater than or equal to a specified minimum value.
  • max: Validates that the input is less than or equal to a specified maximum value.

Follow-up 2

How do you create a custom validator?

To create a custom validator in Angular, you need to create a function that takes a FormControl as an argument and returns an object with a key-value pair indicating the validation result. The key represents the validation error code, and the value can be any truthy value.

Here's an example of a custom validator function that validates if a number is even:

function evenNumberValidator(control: FormControl): { [key: string]: any } | null {
  const value = control.value;
  if (value % 2 !== 0) {
    return { 'evenNumber': true };
  }
  return null;
}

You can then use this custom validator in your form by adding it to the validators array of the form control.

Follow-up 3

How do you display validation error messages?

To display validation error messages in Angular, you can use the ngIf directive along with the errors property of a form control. Here's an example:


<div>
  <div>
    This field is required.
  </div>
  <div>
    Minimum length is 5.
  </div>
</div>

In this example, the error messages are displayed only if the control is invalid, and either dirty or touched. Each error message is conditionally displayed based on the specific error code.

Follow-up 4

How do you validate a form on submit?

To validate a form on submit in Angular, you can use the FormGroup and FormBuilder classes. First, create a FormGroup instance using the FormBuilder and define the form controls with their respective validators. Then, in your submit handler, you can check if the form is valid using the valid property of the FormGroup.

Here's an example:

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

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.myForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.minLength(6)]
    });
  }

  onSubmit() {
    if (this.myForm.valid) {
      // Form is valid, submit data
    } else {
      // Form is invalid, display error messages
    }
  }
}

In this example, the form is considered valid if all the form controls pass their respective validators. If the form is invalid, you can display error messages or take any other appropriate action.

3. What is the difference between template-driven and reactive forms in Angular?

The difference is where the form model lives:

Template-driven Reactive
Module FormsModule ReactiveFormsModule
Model implicit, built from the template (ngModel) explicit, defined in the class (FormGroup/FormControl)
Validation directives in HTML (required, minlength) validator functions in code
Data flow asynchronous synchronous
Testing harder (needs the DOM) easy (test the model directly)
Best for simple, small forms dynamic, complex, typed forms
// reactive: model in the class
form = this.fb.group({ email: ['', Validators.email] });

The guidance interviewers expect: reactive forms are the default recommendation for anything beyond trivial because they're predictable, strongly typed (since v14), and testable. The current twist worth adding: Angular's new signal-based forms (stabilizing in v22) are emerging as a third option that pairs reactive-style explicitness with signal reactivity.

↑ Back to top

Follow-up 1

Which one would you prefer for complex form handling and why?

For complex form handling, I would prefer reactive forms. Reactive forms provide more flexibility and control over form handling. With reactive forms, you can dynamically add or remove form controls, handle complex validation scenarios, and easily manage form state. Reactive forms also provide better testability as the form model can be easily unit tested.

Follow-up 2

How do you handle form validation in each of these?

In template-driven forms, form validation is done using directives such as ngModel and ngForm. These directives provide built-in validation rules and error handling. Custom validation can be implemented using template-driven form validators. In reactive forms, form validation is done using validators provided by the ReactiveForms module. Validators can be applied to individual form controls or to the entire form. Custom validators can also be created and applied to form controls.

Follow-up 3

How do you handle dynamic form fields in each of these?

In template-driven forms, handling dynamic form fields can be a bit more complex. You can use the ngModel directive with ngFor to dynamically generate form controls. However, managing the state and validation of dynamically added form controls can be challenging. In reactive forms, handling dynamic form fields is much easier. You can use the FormArray class to dynamically add or remove form controls. FormArray provides methods to manage the state and validation of dynamically added form controls.

4. What is FormGroup and FormControl in Angular?

They're the core reactive-forms classes:

  • FormControl — represents a single field, tracking its value, validation status, and interaction state (touched/dirty).
  • FormGroup — a keyed collection of controls handled as one unit; its value is an object, and it's valid only when every child is valid.
loginForm = new FormGroup({
  username: new FormControl('', Validators.required),
  password: new FormControl('', Validators.required),
});
// loginForm.value -&gt; { username: '', password: '' }

Round it out by naming FormArray (a dynamic, indexed list of controls — e.g. a variable number of phone numbers) and FormRecord (a dynamic keyed group). A current note: all of these are strictly typed since Angular 14, so value, get(), and setValue() are type-checked, and the same model underpins Angular's new signal-based forms.

↑ Back to top

Follow-up 1

How do you create a FormGroup?

To create a FormGroup, you need to import the FormGroup class from the @angular/forms module and instantiate it in your component.

Here's an example of creating a FormGroup:

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

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      firstName: new FormControl(),
      lastName: new FormControl(),
      email: new FormControl()
    });
  }
}

In this example, we create a FormGroup called myForm with three FormControls: firstName, lastName, and email.

Follow-up 2

How do you link a FormControl to a form field in the template?

To link a FormControl to a form field in the template, you can use the formControlName directive.

Here's an example of linking a FormControl to an input field:




In this example, the formControlName directive is used to bind the firstName FormControl to the input field. This allows Angular to track the value and validation of the input field using the FormControl.

Follow-up 3

How do you access the value of a form field using FormControl?

To access the value of a form field using a FormControl, you can use the value property of the FormControl.

Here's an example of accessing the value of a form field:

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

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      firstName: new FormControl()
    });
  }

  onSubmit() {
    const firstNameValue = this.myForm.get('firstName').value;
    console.log(firstNameValue);
  }
}

In this example, we access the value of the firstName form field using the value property of the FormControl. The value is then logged to the console.

5. How do you handle form submission in Angular?

Bind the form's (ngSubmit) event to a handler — it fires on a type="submit" button and Angular prevents the default page reload:



  Submit

onSubmit() {
  if (this.form.invalid) {
    this.form.markAllAsTouched();   // reveal validation messages
    return;
  }
  this.api.save(this.form.getRawValue());
}

Key points: use (ngSubmit) (not a button click) so Enter-to-submit works; check validity and markAllAsTouched() before processing; and disable the submit button while invalid or while a request is in flight. For template-driven forms it's the same event, with #f="ngForm" giving you access to the form's value and validity.

↑ Back to top

Follow-up 1

How do you get the form values on submission?

To get the form values on submission in Angular, you can use the NgForm directive along with the ngModel directive. Here is an example:



  Submit

In the above example, the [(ngModel)] directive is used to bind the input field value to the name property in the component. The myForm parameter in the onSubmit() method is of type NgForm, which gives you access to the form values.

Follow-up 2

How do you handle form reset after submission?

To handle form reset after submission in Angular, you can use the reset() method of the NgForm directive. Here is an example:



  Submit

onSubmit(myForm: NgForm) {
  // form submission logic
  myForm.reset();
}

In the above example, the myForm.reset() method is called in the onSubmit() method to reset the form after submission. This will clear all the form fields and set them to their initial values.

Follow-up 3

How do you prevent the default form submission behavior?

To prevent the default form submission behavior in Angular, you can use the event.preventDefault() method. Here is an example:

onSubmit(event: Event) {
  event.preventDefault();
  // form submission logic
}

In the above example, the event.preventDefault() method is called to prevent the default form submission behavior. You can then implement your own form submission logic.

Live mock interview

Mock interview: Form Control and Validation

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.