<?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 Gugan Arumugam on Medium]]></title>
        <description><![CDATA[Stories by Gugan Arumugam on Medium]]></description>
        <link>https://medium.com/@guganarumugam93?source=rss-c61547923dba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jWt4b3Jcpx-JljQX7ZqJIQ.jpeg</url>
            <title>Stories by Gugan Arumugam on Medium</title>
            <link>https://medium.com/@guganarumugam93?source=rss-c61547923dba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:35:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guganarumugam93/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[Angular Nested Reactive Forms — Using CVAs]]></title>
            <link>https://medium.com/angular-in-depth/angular-nested-reactive-forms-using-cvas-b394ba2e5d0d?source=rss-c61547923dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b394ba2e5d0d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Gugan Arumugam]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 10:32:04 GMT</pubDate>
            <atom:updated>2020-04-29T21:30:32.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular: Nested Reactive Forms Using ControlValueAccessors(CVAs)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rn_VVGtR_JZPNskJ" /><figcaption>Photo by <a href="https://unsplash.com/@dankapeter?utm_source=medium&amp;utm_medium=referral">Danka &amp; Peter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*vtU5ye6glSnON_St.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>In this post, we will see how to implement nested reactive forms using composite control value accessors(CVAs). <a href="https://twitter.com/karaforthewin?lang=en"><strong>Kara Erickson</strong></a><strong> of the Angular Core Team presented this approach at the A</strong><a href="https://youtu.be/CD_t3m2WMM8"><strong>ngular Connect 2017 </strong></a><strong>.</strong></p><h3>Three Ways to implement nested forms:</h3><p>We will see the most commonly used techniques to implement nested forms.</p><ol><li>Sub -Form Component Approach (providing ControlContainer)</li></ol><p>It is built differently for template and reactive driven forms.</p><blockquote>Best when you have a really small project and you are using one form module only and you just have to split out a really long form(Excerpt from the talk).</blockquote><blockquote>Pro: Quicker to setup and run.</blockquote><blockquote>Con: Limited to one form module.</blockquote><p>2. By passing a handle of the FormGroup to child components via Inputand referencing it in child templates. There are couple of good tutorials on it.</p><blockquote>But the con of using this approach is that you are tightly binding the parent form group with that of child group.</blockquote><p>3. Using Composite CVAs.</p><blockquote>Pros: Highly Reusable, Portable. Better Encapsulation(Internal Form Controls of the component doesn’t necessarily need to be visible to parent components). <strong>This is best used when you have more number of form modules which is typically a large project</strong>.</blockquote><blockquote>Cons: Need to implement CVA interface results in boilerplate code.</blockquote><p>This is what we are going to see now.</p><h3>What is Control Value Accessor (CVA)?</h3><p>Here’s what the developers at Google - Angular have to say on this?</p><blockquote>The ControlValueAccessor interface is actually what you use to build value accessors for radio buttons, selects, input elements etc in core. It just requires three methods:</blockquote><blockquote>writeValue(value: any): void : takes a value and writes it to the form control element (model -&gt; view)</blockquote><blockquote>registerOnChange(fn: (value:any) =&gt; void): void: takes a function that should be called with the value if the value changes in the form control element itself (view -&gt; model)</blockquote><blockquote>registerOnTouched(fn: () =&gt; void): takes a function to be called when the form control has been touched (this one you can leave empty if you don’t care about the touched property)</blockquote><p><em>If you want to know more in-depth or if you are still confused about implementing one , </em><a href="https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-in-angular-forms-93b9eee9ee83"><em>read this article by Max, from Angular-In-Depth</em></a></p><h3>Implementing Composite CVAs</h3><p>This section assumes that you have a working knowledge on Reactive Forms mainly FormGroups, FormControls, Validations etc.</p><p>I have created a sample reactive form component called billing-info-unnested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8e8c73ab825dc86f0501e20952ec528/href">https://medium.com/media/f8e8c73ab825dc86f0501e20952ec528/href</a></iframe><p>Output:</p><pre>nestedForm {<br>fname:&quot;&quot;,<br>email: &quot;&quot;,<br>addressLine: &quot;&quot;,<br>areacode: &quot;&quot;<br>}</pre><p>Now imagine, if our client introduces few more requirements and we need to reuse these controls along with few more form field additions such as.</p><blockquote>For checkout form: Shipping types.</blockquote><blockquote>For signin/registration: Password, gender, age, etc.</blockquote><p>In this scenario, We can reuse by grouping them into components and converting them as form controls. That is, we are going to build our component as a composite control value accessor. We can even provide validations at the component levels. This technique is amazing, trust me. :D</p><p>Lets move <em>name </em>and <em>email </em>into BasicInfoComponent , and <em>addressLine </em>and <em>areacode </em>into <em>AddressComponent.</em></p><p>Here we are taking BasicInfoComponent as example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce81466989ae0092e0b96eb310342726/href">https://medium.com/media/ce81466989ae0092e0b96eb310342726/href</a></iframe><p>The .ts file looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64acfbd3babb060f1f5880062f2bcf01/href">https://medium.com/media/64acfbd3babb060f1f5880062f2bcf01/href</a></iframe><p>Output:</p><pre>basicInfoForm: {<br>fname: &quot;&quot;,<br>email: &quot;&quot;<br>}</pre><p>Similarly do the same for AddressComponent.</p><p>Now the parent form component BillingInfo will look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d425695b278fb193c2f062666f28523/href">https://medium.com/media/8d425695b278fb193c2f062666f28523/href</a></iframe><p>Now lets try to run this. Here is the <a href="https://stackblitz.com/edit/angular-simple-reactive-forms-vu1mcy">Stackblitz demo</a></p><h3>Error !</h3><p>When we try to run the demo, we will encounter error unfortunately.</p><blockquote>Error: No value accessor for form control with name: ‘basicInfo’</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fga9ngPY2zWlp4M4hi864Q.png" /></figure><p>Lets take a look at the <strong>built-in value accessors</strong> provided by the Angular Core.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742973172f1fbc2e6a68ea8564e8cf78/href">https://medium.com/media/742973172f1fbc2e6a68ea8564e8cf78/href</a></iframe><p>Since our form control (component) doesn’t falls in any these categories, angular compiler throws error stating no value accessor is found.</p><blockquote><strong>If you want your custom form control to integrate with Angular forms, it has to implement ControlValueAccessor</strong></blockquote><h3>Integrate Custom Form Controls into Angular Forms</h3><p>Lets implement interface <strong>ControlValueAccessor</strong> and override all the methods in our BasicInfoComponent and AddressInfoComponent. This is what AddressComponent looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/924295eb804e071bd38a34fc72dc0225/href">https://medium.com/media/924295eb804e071bd38a34fc72dc0225/href</a></iframe><p>After implementing accessor, we need to tell angular, that for &lt;app-address-info&gt;&lt;/app-address-info&gt; form control element, this is its relevant control value accessor.</p><h4>How can we achieve that?</h4><p>Lets take a look at how DefaultValueAccessor is provided in the <a href="https://github.com/angular/angular/blob/master/packages/forms/src/directives/default_value_accessor.ts#L13">Angular Forms Package</a>.</p><pre>export const DEFAULT_VALUE_ACCESSOR: any = {  <br>provide: NG_VALUE_ACCESSOR,  <br>useExisting: forwardRef(() =&gt; DefaultValueAccessor),  <br>multi: true<br>};</pre><p>Lets dissect the syntax above.</p><ol><li>Here the DefaultValueAccessor is registered using the built-in token NG_VALUE_ACCESSOR.</li><li>fowardRef() denotes <em>refer to references which are not yet defined. Use the instance of</em>DefaultValueAccessor <em>which will be later instantiated by Angular</em></li><li>useExisting() is used to make sure there is only one instance of DefaultValueAccessor.</li><li>The provider object has a third option, multi: true, which is used with DI Tokens to register multiple handlers for the provide event.This is useful if we want to register our custom CVAs to NG_VALUE_ACCESSOR token</li></ol><blockquote><a href="https://blog.angularindepth.com/what-is-forwardref-in-angular-and-why-we-need-it-6ecefb417d48">For more info about forwardRef() there is again this great article by Max, from Angular-in-depth</a></blockquote><p>Now we will do the same for our BasicInfoComponent and AddressInfoComponent and run the demo again.</p><p><a href="https://stackblitz.com/edit/angular-simple-reactive-forms-cawhs7"><em>StackBlitz demo after implementing CVAs</em></a></p><p>We see that our error is gone. Hooray!! We have successfully integrated our nested child form control into our Angular Core. But there is still one problem.</p><p>Even though our place order button should be disabled if the form is invalid, we see it is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*h04e0QrWSizeLiEhk3dB0Q.png" /></figure><p>Below is the html code</p><pre>&lt;button type=”submit” [disabled]=”nestedForm.invalid”&gt;Place Order&lt;/button&gt;</pre><p>So lets Inspect in developer tools.</p><h4>Validation Status of Child Components is failing</h4><p>On Inspect, we can see that custom form control(child component)&lt;app-basic-info&gt;&lt;/app-basic-info&gt; status is valid, while the form controls inside the basic-info component are still invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WISfBLTv6I-XfOKvwmm0AQ.png" /></figure><p>In the previous section, we learnt that</p><blockquote><strong>If you want your custom form control to integrate with Angular forms, it has to implement </strong>ControlValueAccessor<strong>.</strong></blockquote><blockquote><strong>Now, if we want that integration to include validation, we need to implement the </strong>Validator<strong> interface as well and provide our custom control as a multi provider to built-in </strong>NG_VALIDATOR <strong>token.</strong></blockquote><h4>Reason:</h4><blockquote>For Re-validation, the validators will need to be on the top-level form, not at the child component, if you want it to be part of the parent form’s validation.</blockquote><p>In our case we need to have validators at BillingInfoComponent level, so for this purpose we need to convert our component to act as a <strong>validator directives</strong> such as required, min, max etc.</p><p>So lets implement Validator interface in our child components.</p><p>Take a look at how <a href="https://github.com/angular/angular/blob/master/packages/forms/src/directives/validators.ts#L118">required directive is provided in angular forms package</a>.</p><pre>export const REQUIRED_VALIDATOR: StaticProvider = {  <br>provide: NG_VALIDATORS,  <br>useExisting: forwardRef(() =&gt; RequiredValidator),  <br>multi: true };</pre><p>We need to do the same for our custom form validator. We need to register a custom form validator using the built-in <a href="https://angular.io/api/forms/NG_VALIDATORS">NG_VALIDATORS</a> token, and provide multiples instance of our validator provider by using the multi: true property in the provider object. This tells Angular to add our custom validators to the existing collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/594ef658f18312930f9ca048c5bf66bf/href">https://medium.com/media/594ef658f18312930f9ca048c5bf66bf/href</a></iframe><p>So by doing this we get &lt;app-basic-info&gt;&lt;/app-basic-info&gt; and &lt;app-address-info&gt;&lt;/app-basic-info&gt; <strong>re-validated</strong>(by calling validate method which in turn validates all the form controls present inside that child component) and status is sent to the parent form component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m65urEnQwJ2usdGzu9kMFw.png" /></figure><p>Bazinga!! we have accomplished it.</p><p><a href="https://stackblitz.com/edit/angular-nested-forms-cva"><strong>Here is the full stack blitz demo</strong></a></p><h4>Thanks for reading! Your feedback is most welcome. If you liked this article, hit that clap button.</h4><h4><strong>Follow me </strong><a href="https://twitter.com/guganarumugam93"><strong>twitter </strong></a><strong>if you want to say “hi” or talk about music.</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b394ba2e5d0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/angular-nested-reactive-forms-using-cvas-b394ba2e5d0d">Angular Nested Reactive Forms — Using CVAs</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>