<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: krishna</title>
    <description>The latest articles on DEV Community by krishna (@krishhnaa).</description>
    <link>https://dev.to/krishhnaa</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F271346%2F2b10c930-774e-45a1-adf4-2447a588cf72.png</url>
      <title>DEV Community: krishna</title>
      <link>https://dev.to/krishhnaa</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/krishhnaa"/>
    <language>en</language>
    <item>
      <title>Understanding angular ControlValueAccessor with an example</title>
      <dc:creator>krishna</dc:creator>
      <pubDate>Tue, 09 May 2023 00:16:26 +0000</pubDate>
      <link>https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-with-an-example-33gb</link>
      <guid>https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-with-an-example-33gb</guid>
      <description>&lt;p&gt;In my previous &lt;a href="https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-482h"&gt;article&lt;/a&gt;, I explained the ControlValueAccessor Interface now lets deep dive with an example.&lt;/p&gt;

&lt;p&gt;Let’s say you have a custom input component that is meant to accept phone numbers in a specific format, such as &lt;code&gt;(123) 456–8799&lt;/code&gt;. You want to create a custom form control that will enforce this format and allow for easy data binding to the component.&lt;/p&gt;

&lt;p&gt;To achieve this, you can create a ControlValueAccessor for the custom input component. The ControlValueAccessor interface defines four methods that you need to implement: &lt;code&gt;writeValue()&lt;/code&gt;, &lt;code&gt;registerOnChange()&lt;/code&gt;, &lt;code&gt;registerOnTouched()&lt;/code&gt;, and &lt;code&gt;setDisabledState()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here’s an example implementation of the &lt;code&gt;ControlValueAccessor&lt;/code&gt; interface for our custom phone number input component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-phone-number-input',
  templateUrl: './phone-number-input.component.html',
  styleUrls: ['./phone-number-input.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() =&amp;gt; PhoneNumberInputComponent),
      multi: true
    }
  ]
})
export class PhoneNumberInputComponent implements ControlValueAccessor {
  myForm! : FormGroup;
  private onChange: (value: string) =&amp;gt; void;
  private onTouched: () =&amp;gt; void;

  public phoneNumber: string;

   constructor(private fb: FormBuilder) { 
    this.myForm = this.fb.group({
       // implement the formcontrol
    })
   }
  public writeValue(value: string): void {
    this.phoneNumber = value;
  }

  public registerOnChange(fn: (value: string) =&amp;gt; void): void {
    this.onChange = fn;
  }

  public registerOnTouched(fn: () =&amp;gt; void): void {
    this.onTouched = fn;
  }

  public setDisabledState?(isDisabled: boolean): void {
    // Implement if needed
  }

  public onPhoneNumberChanged(): void {
    // enforce the phone number format
    const formattedPhoneNumber = this.phoneNumber.replace(/[^0-9]/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
    this.phoneNumber = formattedPhoneNumber;

    // notify the form control that the value has changed
    this.onChange(formattedPhoneNumber);
  }

  public onBlur(): void {
    this.onTouched();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we first import &lt;code&gt;ControlValueAccessor&lt;/code&gt; and &lt;code&gt;NG_VALUE_ACCESSOR&lt;/code&gt; from the @angular/forms module. We then implement the ControlValueAccessor interface in our PhoneNumberInputComponent class.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;writeValue()&lt;/code&gt; method is called by the Angular forms API when the value of the form control is updated. We simply set the phoneNumber property to the value passed in.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;registerOnChange()&lt;/code&gt; and &lt;code&gt;registerOnTouched()&lt;/code&gt; methods are used to register callback functions that Angular calls when the value or touched state of the control changes. We store these callback functions in private class properties &lt;code&gt;onChange&lt;/code&gt; and &lt;code&gt;onTouched&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;setDisabledState()&lt;/code&gt; method is optional and can be implemented if you want to disable the input control.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;onPhoneNumberChanged()&lt;/code&gt; method is called whenever the phone number input value changes. We enforce the phone number format by replacing all non-numeric characters and formatting the string with parentheses and hyphens. We then call the onChange() method with the formatted phone number to notify the form control that the value has changed.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;onBlur()&lt;/code&gt; method is called whenever the input control loses focus. We call the &lt;code&gt;onTouched()&lt;/code&gt; method to notify the form control that the input has been touched.&lt;/p&gt;

&lt;p&gt;By implementing the &lt;code&gt;ControlValueAccessor&lt;/code&gt; interface, our custom phone number input component can be easily used in a reactive form. In the above code, we first import &lt;code&gt;ControlValueAccessor&lt;/code&gt; and &lt;code&gt;NG_VALUE_ACCESSOR&lt;/code&gt; from the &lt;code&gt;@angular/forms&lt;/code&gt; module. We then implement the ControlValueAccessor interface in our &lt;code&gt;PhoneNumberInputComponent&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;writeValue()&lt;/code&gt; method is called by the Angular forms API when the value of the form control is updated. We simply set the phoneNumber property to the value passed in.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;registerOnChange()&lt;/code&gt; and &lt;code&gt;registerOnTouched()&lt;/code&gt; methods are used to register callback functions that Angular calls when the value or touched state of the control changes. We store these callback functions in private class properties onChange and onTouched.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;setDisabledState()&lt;/code&gt; method is optional and can be implemented if you want to disable the input control.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;onPhoneNumberChanged()&lt;/code&gt; method is called whenever the phone number input value changes. We enforce the phone number format by replacing all non-numeric characters and formatting the string with parentheses and hyphens. We then call the onChange() method with the formatted phone number to notify the form control that the value has changed.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;onBlur()&lt;/code&gt; method is called whenever the input control loses focus. We call the onTouched() method to notify the form control that the input has been touched.&lt;/p&gt;

&lt;p&gt;By implementing the &lt;code&gt;ControlValueAccessor&lt;/code&gt; interface, our custom phone number input component can be easily used in a reactive form.&lt;/p&gt;

&lt;p&gt;And in the template, you will create a form with &lt;code&gt;FormGroup&lt;/code&gt; where you will specify the component and use the &lt;code&gt;app-phone-number-input&lt;/code&gt; like the below example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form [formGroup]="myForm"&amp;gt;
  &amp;lt;label for="phone"&amp;gt;Phone number:&amp;lt;/label&amp;gt;
  &amp;lt;app-phone-number-input formControlName="phone"&amp;gt;&amp;lt;/app-phone-number-input&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we first create a &lt;code&gt;FormGroup&lt;/code&gt; in our component's class and assign it to the formGroup attribute of the &lt;code&gt;&amp;lt;form&amp;gt;&lt;/code&gt; element.&lt;/p&gt;

&lt;p&gt;We then create a label for the phone number input and use the &lt;code&gt;formControlName&lt;/code&gt; directive to bind the phone number input to the "phone" form control.&lt;/p&gt;

&lt;p&gt;Finally, we use the &lt;code&gt;&amp;lt;app-phone-number-input&amp;gt;&lt;/code&gt; custom input component and pass it the "phone" form control.&lt;/p&gt;

&lt;p&gt;Now, whenever the phone number input value changes, the &lt;code&gt;onPhoneNumberChanged()&lt;/code&gt; method in our &lt;code&gt;PhoneNumberInputComponent&lt;/code&gt; will be called, and the value will be propagated to the "phone" form control through the &lt;code&gt;onChange()&lt;/code&gt; callback.&lt;/p&gt;

&lt;p&gt;Similarly, whenever the input loses focus, the &lt;code&gt;onBlur()&lt;/code&gt; method will be called, and the onTouched() callback will be called to mark the control as touched.&lt;/p&gt;

&lt;p&gt;Note that you also need to import the &lt;code&gt;ReactiveFormsModule&lt;/code&gt; in your module in order to use reactive forms in your application&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>angular</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding Angular ControlValueAccessor</title>
      <dc:creator>krishna</dc:creator>
      <pubDate>Mon, 08 May 2023 19:04:06 +0000</pubDate>
      <link>https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-482h</link>
      <guid>https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-482h</guid>
      <description>&lt;p&gt;Today I am going to explain What is &lt;strong&gt;ControlValueAccessor&lt;/strong&gt; in Angular, its advantage and why I chose &lt;strong&gt;ControlValueAccessor&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Angular &lt;code&gt;ControlValueAccessor&lt;/code&gt; 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.&lt;/p&gt;

&lt;p&gt;To use Angular ControlValueAccessor, you need to implement it in your custom form control. The interface consists of two methods:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;writeValue()&lt;/strong&gt;&lt;/em&gt;: 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.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;registerOnChange()&lt;/em&gt;&lt;/strong&gt;: 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.&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
Here is an example of how to implement Angular Control Accessor in a custom form control:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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(() =&amp;gt; CustomInputComponent),
      multi: true,
    },
  ],
})
export class CustomInputComponent implements ControlValueAccessor {
  value: string;

  onChange = (value: string) =&amp;gt; {};
  onTouched = () =&amp;gt; {};

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

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

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;The &lt;code&gt;writeValue()&lt;/code&gt; method updates the value of the custom form control and calls the onChange() callback function.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;registerOnChange()&lt;/code&gt; method registers the onChange() callback function.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;registerOnTouched()&lt;/code&gt; method registers the onTouched() callback function, which is called when the custom form control is touched.&lt;/p&gt;

&lt;p&gt;With Angular &lt;code&gt;ControlValueAccessor&lt;/code&gt; interface, you can create powerful and flexible custom form controls that can be used seamlessly with Angular Forms.&lt;/p&gt;

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

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;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.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;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.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;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.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;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.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;In my next &lt;a href="https://dev.to/krishhnaa/understanding-angular-controlvalueaccessor-with-an-example-33gb"&gt;article&lt;/a&gt;, let’s see an example on how we use &lt;code&gt;ControlValueAccessor&lt;/code&gt; Interface.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
