Form Control and Validation

Understanding form control and validation in Angular.

Form Control and Validation Interview with follow-up questions

Question 1: What is form control in Angular?

Answer:

In Angular, a form control is an object that binds to a form element and manages the form's data. It tracks the value and validation status of an individual form control, such as an input field or a select dropdown.

Back to Top ↑

Follow up 1: How do you create a form control instance?

Answer:

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();
Back to Top ↑

Follow up 2: What are the key properties of a form control?

Answer:

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.
Back to Top ↑

Follow up 3: How do you set value in form control?

Answer:

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');
Back to Top ↑

Follow up 4: How do you reset a form control?

Answer:

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

myFormControl.reset();
Back to Top ↑

Question 2: What is form validation in Angular?

Answer:

Form validation in Angular is the process of ensuring that user input in a form meets certain criteria or constraints. It helps to ensure that the data entered by the user is valid and complete before it is submitted to the server.

Back to Top ↑

Follow up 1: What are the built-in validators in Angular?

Answer:

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.
Back to Top ↑

Follow up 2: How do you create a custom validator?

Answer:

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.

Back to Top ↑

Follow up 3: How do you display validation error messages?

Answer:

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.

Back to Top ↑

Follow up 4: How do you validate a form on submit?

Answer:

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.

Back to Top ↑

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

Answer:

Template-driven forms in Angular are built using Angular's template syntax and are mainly driven by the template itself. The form controls and validation rules are defined directly in the HTML template. On the other hand, reactive forms are built using the ReactiveForms module and are mainly driven by the underlying form model. The form controls and validation rules are defined programmatically in the component class.

Back to Top ↑

Follow up 1: Which one would you prefer for complex form handling and why?

Answer:

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.

Back to Top ↑

Follow up 2: How do you handle form validation in each of these?

Answer:

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.

Back to Top ↑

Follow up 3: How do you handle dynamic form fields in each of these?

Answer:

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.

Back to Top ↑

Question 4: What is FormGroup and FormControl in Angular?

Answer:

FormGroup and FormControl are classes in Angular used for handling form data.

FormGroup is a class that represents a collection of form controls. It is used to group related form controls together and track the validation and value of the group as a whole.

FormControl is a class that represents an individual form control, such as an input field or a select dropdown. It is used to track the validation and value of the control.

Back to Top ↑

Follow up 1: How do you create a FormGroup?

Answer:

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.

Back to Top ↑

Follow up 2: How do you link a FormControl to a form field in the template?

Answer:

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.

Back to Top ↑

Follow up 3: How do you access the value of a form field using FormControl?

Answer:

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.

Back to Top ↑

Question 5: How do you handle form submission in Angular?

Answer:

To handle form submission in Angular, you can use the ngSubmit directive. Here is an example of how to use it:



  Submit

In the above example, the onSubmit() method will be called when the form is submitted. You can define this method in your component to handle the form submission logic.

Back to Top ↑

Follow up 1: How do you get the form values on submission?

Answer:

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.

Back to Top ↑

Follow up 2: How do you handle form reset after submission?

Answer:

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.

Back to Top ↑

Follow up 3: How do you prevent the default form submission behavior?

Answer:

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.

Back to Top ↑