DEV Community

krishna
krishna

Posted on

Understanding Angular ControlValueAccessor

Today I am going to explain What is ControlValueAccessor in Angular, its advantage and why I chose ControlValueAccessor.

Angular ControlValueAccessor is an interface in Angular that is used to bridge the gap between Angular Forms and custom form controls. This interface provides a way for custom form controls to communicate with Angular Forms, allowing them to be used in template-driven and reactive forms.

To use Angular ControlValueAccessor, you need to implement it in your custom form control. The interface consists of two methods:

writeValue(): This method is used to update the value of the custom form control. When this method is called, the new value is passed as an argument.

registerOnChange(): This method is used to register a callback function that will be called whenever the value of the custom form control changes. The callback function is passed as an argument.

By implementing these methods, your custom form control can now be used in template-driven and reactive forms just like any other built-in form control.
Here is an example of how to implement Angular Control Accessor in a custom form control:

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true,
    },
  ],
})
export class CustomInputComponent implements ControlValueAccessor {
  value: string;

  onChange = (value: string) => {};
  onTouched = () => {};

  writeValue(value: string): void {
    this.value = value;
    this.onChange(value);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have implemented the ControlValueAccessor interface in our custom form control, CustomInputComponent. We have also provided this component to the NG_VALUE_ACCESSOR injection token, which makes it available for use in Angular Forms.

The writeValue() method updates the value of the custom form control and calls the onChange() callback function.

The registerOnChange() method registers the onChange() callback function.

The registerOnTouched() method registers the onTouched() callback function, which is called when the custom form control is touched.

With Angular ControlValueAccessor interface, you can create powerful and flexible custom form controls that can be used seamlessly with Angular Forms.

So far we saw what is ControlValueAccessor with example and the explanation of the each method. Now, I am going to write some benefits of using Angular ControlValueAccessors.

  1. ControlValueAccessors provide a standard interface for accessing and manipulating form control values, status, and errors. This makes it easier to work with form controls in a consistent way, regardless of the specific type of control or how it is implemented.

  2. By using ControlValueAccessors, you can create custom form controls that can be used in templates and validated in the same way as built-in form controls. This allows you to create more flexible and reusable components for forms.

  3. ControlValueAccessors allow you to create custom validators that can be used with any form control. This can simplify the validation code for your forms, and make it easier to write and maintain.

  4. Using ControlValueAccessors can improve the performance of your forms by reducing the number of change detection cycles required. This is because control accessors allow you to manually trigger change detection only when needed, rather than relying on Angular’s default change detection behavior.

Overall, using ControlValueAccessors can simplify and improve the development of forms in Angular applications, and provide a more consistent and flexible way to work with form controls.

In my next article, let’s see an example on how we use ControlValueAccessor Interface.

Top comments (3)

Collapse
 
danielhe4rt profile image
Daniel Reis • Edited

Nice article! Try to use

console.log("hey!")
Enter fullscreen mode Exit fullscreen mode

markdown tag in your next post to make it fancier 😎

Keep sharing!

Collapse
 
krishhnaa profile image
krishna

Thank you for your time. I just realized after publishing and updated, please take a look.

Collapse
 
danielhe4rt profile image
Daniel Reis

Try to add into your codeblock at the beginning the language that you want to highlight.

console.log('php is better :p')
Enter fullscreen mode Exit fullscreen mode

Image description