<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by krishna on Medium]]></title>
        <description><![CDATA[Stories by krishna on Medium]]></description>
        <link>https://medium.com/@krishyalla?source=rss-69a223e508cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yjX2FAGV7fv_3fmM.jpeg</url>
            <title>Stories by krishna on Medium</title>
            <link>https://medium.com/@krishyalla?source=rss-69a223e508cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:57:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishyalla/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding angular ControlValueAccessor with an example]]></title>
            <link>https://medium.com/@krishyalla/understanding-angular-controlvalueaccessor-with-an-example-7bca7afd017f?source=rss-69a223e508cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bca7afd017f</guid>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[angular-reactive-form]]></category>
            <dc:creator><![CDATA[krishna]]></dc:creator>
            <pubDate>Mon, 08 May 2023 23:52:20 GMT</pubDate>
            <atom:updated>2023-05-09T13:59:07.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hfUr5sOx0Sn_IgXP" /></figure><p>In my previous <a href="https://medium.com/@krishyalla/understanding-angular-controlvalueaccessor-4fab61443606">article</a>, I explained the ControlValueAccessor Interface now lets deep dive with an example.</p><p>Let’s say you have a custom input component that is meant to accept phone numbers in a specific format, such as “(123) 456–8799”. You want to create a custom form control that will enforce this format and allow for easy data binding to the component.</p><p>To achieve this, you can create a ControlValueAccessor for the custom input component. The ControlValueAccessor interface defines four methods that you need to implement: writeValue(), registerOnChange(), registerOnTouched(), and setDisabledState().</p><p>Here’s an example implementation of the ControlValueAccessor interface for our custom phone number input component:</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-phone-number-input&#39;,<br>  templateUrl: &#39;./phone-number-input.component.html&#39;,<br>  styleUrls: [&#39;./phone-number-input.component.css&#39;],<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; PhoneNumberInputComponent),<br>      multi: true<br>    }<br>  ]<br>})<br>export class PhoneNumberInputComponent implements ControlValueAccessor {<br>  myForm! : FormGroup;<br>  private onChange: (value: string) =&gt; void;<br>  private onTouched: () =&gt; void;<br><br>  public phoneNumber: string;<br>   <br>   constructor(private fb: FormBuilder) { <br>    this.myForm = this.fb.group({<br>       // implement the formcontrol<br>    })<br>   }<br>  public writeValue(value: string): void {<br>    this.phoneNumber = value;<br>  }<br><br>  public registerOnChange(fn: (value: string) =&gt; void): void {<br>    this.onChange = fn;<br>  }<br><br>  public registerOnTouched(fn: () =&gt; void): void {<br>    this.onTouched = fn;<br>  }<br><br>  public setDisabledState?(isDisabled: boolean): void {<br>    // Implement if needed<br>  }<br><br>  public onPhoneNumberChanged(): void {<br>    // enforce the phone number format<br>    const formattedPhoneNumber = this.phoneNumber.replace(/[^0-9]/g, &#39;&#39;).replace(/(\d{3})(\d{3})(\d{4})/, &#39;($1) $2-$3&#39;);<br>    this.phoneNumber = formattedPhoneNumber;<br>    <br>    // notify the form control that the value has changed<br>    this.onChange(formattedPhoneNumber);<br>  }<br><br>  public onBlur(): void {<br>    this.onTouched();<br>  }<br>}</pre><p>In the above code, we first import ControlValueAccessor and NG_VALUE_ACCESSOR from the @angular/forms module. We then implement the ControlValueAccessor interface in our PhoneNumberInputComponent class.</p><p>The writeValue() 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.</p><p>The registerOnChange() and registerOnTouched() 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.</p><p>The setDisabledState() method is optional and can be implemented if you want to disable the input control.</p><p>The onPhoneNumberChanged() 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.</p><p>The onBlur() 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.</p><p>By implementing the ControlValueAccessor interface, our custom phone number input component can be easily used in a reactive form. In the above code, we first import ControlValueAccessor and NG_VALUE_ACCESSOR from the @angular/forms module. We then implement the ControlValueAccessor interface in our PhoneNumberInputComponent class.</p><p>The writeValue() 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.</p><p>The registerOnChange() and registerOnTouched() 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.</p><p>The setDisabledState() method is optional and can be implemented if you want to disable the input control.</p><p>The onPhoneNumberChanged() 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.</p><p>The onBlur() 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.</p><p>By implementing the ControlValueAccessor interface, our custom phone number input component can be easily used in a reactive form.</p><p>And in the template, you will create a form with FormGroup where you will specify the component and use the app-phone-number-input like the below example.</p><pre>&lt;form [formGroup]=&quot;myForm&quot;&gt;<br>  &lt;label for=&quot;phone&quot;&gt;Phone number:&lt;/label&gt;<br>  &lt;app-phone-number-input formControlName=&quot;phone&quot;&gt;&lt;/app-phone-number-input&gt;<br>&lt;/form&gt;</pre><p>In the above code, we first create a FormGroup in our component&#39;s class and assign it to the formGroup attribute of the &lt;form&gt; element.</p><p>We then create a label for the phone number input and use the formControlName directive to bind the phone number input to the &quot;phone&quot; form control.</p><p>Finally, we use the &lt;app-phone-number-input&gt; custom input component and pass it the &quot;phone&quot; form control.</p><p>Now, whenever the phone number input value changes, the onPhoneNumberChanged() method in our PhoneNumberInputComponent will be called, and the value will be propagated to the &quot;phone&quot; form control through the onChange() callback.</p><p>Similarly, whenever the input loses focus, the onBlur() method will be called, and the onTouched() callback will be called to mark the control as touched.</p><p>Note that you also need to import the ReactiveFormsModule in your module in order to use reactive forms in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bca7afd017f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular ControlValueAccessor]]></title>
            <link>https://medium.com/@krishyalla/understanding-angular-controlvalueaccessor-4fab61443606?source=rss-69a223e508cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fab61443606</guid>
            <dc:creator><![CDATA[krishna]]></dc:creator>
            <pubDate>Mon, 08 May 2023 15:45:46 GMT</pubDate>
            <atom:updated>2023-05-09T13:39:33.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Angular controlValueAccessor" src="https://cdn-images-1.medium.com/max/1024/0*-5_D7dRnhAS0XjiO" /></figure><p>Today I am going to explain What are ControlValueAccessor in Angular, its advantage and why I chose ControlValueAccessor.</p><p>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.</p><p>To use Angular `ControlValueAccessor`, you need to implement it in your custom form control. The interface consists of two methods:</p><ol><li>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.</li><li>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.</li><li>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.</li></ol><p>Here is an example of how to implement Angular `ControlValueAccessor` in a custom form control:</p><pre>import { Component, forwardRef } from &#39;@angular/core&#39;;<br>import { ControlValueAccessor, NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-custom-input&#39;,<br>  templateUrl: &#39;./custom-input.component.html&#39;,<br>  providers: [<br>    {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; CustomInputComponent),<br>      multi: true,<br>    },<br>  ],<br>})<br>export class CustomInputComponent implements ControlValueAccessor {<br>  value: string;<br><br>  onChange = (value: string) =&gt; {};<br>  onTouched = () =&gt; {};<br><br>  writeValue(value: string): void {<br>    this.value = value;<br>    this.onChange(value);<br>  }<br><br>  registerOnChange(fn: any): void {<br>    this.onChange = fn;<br>  }<br><br>  registerOnTouched(fn: any): void {<br>    this.onTouched = fn;<br>  }<br>}</pre><p>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.</p><p>The writeValue() method updates the value of the custom form control and calls the onChange() callback function.</p><p>The registerOnChange() method registers the onChange() callback function.</p><p>The registerOnTouched() method registers the onTouched() callback function, which is called when the custom form control is touched.</p><p>With Angular `ControlValueAccessor`, you can create powerful and flexible custom form controls that can be used seamlessly with Angular Forms.</p><p>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.</p><ol><li><strong>ControlValueAccessors</strong> 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.</li><li>By using <strong>ControlValueAccessors</strong>, 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.</li><li><strong>ControlValueAccessors</strong> 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.</li><li>Using <strong>ControlValueAccessors</strong> 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.</li></ol><p>Overall, using <strong>ControlValueAccessors </strong>can simplify and improve the development of forms in Angular applications, and provide a more consistent and flexible way to work with form controls.</p><p>In my next <a href="https://medium.com/@krishyalla/understanding-angular-controlvalueaccessor-with-an-example-7bca7afd017f">article</a> <strong>, </strong>let’s see an example on how we use <strong>ControlValueAccessor</strong> Interface</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fab61443606" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>