{"id":2633,"date":"2023-04-19T17:25:26","date_gmt":"2023-04-19T15:25:26","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=2633"},"modified":"2023-04-28T14:39:19","modified_gmt":"2023-04-28T12:39:19","slug":"forwarding-formcontrolname-to-custom-components-in-angular-in-reactive-form","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2023\/04\/19\/forwarding-formcontrolname-to-custom-components-in-angular-in-reactive-form\/","title":{"rendered":"Angular : Implementing  Control Value Accessor"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<p>Let&#8217;s assume we create a custom (angular) Component  &#8220;custom-select&#8221;  in a reactive form and want to use it like below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;div &#91;formGroup]=\"filterFormControls\"&gt;\n   &lt;custom-select &#91;items]=\"selectItems\" formControlName=\"country\"&gt;&lt;\/custom-select&gt;\n&lt;\/div&gt;\n<\/code><\/pre>\n\n\n\n<p>If we yet try to transpile the code, we will get the following errors :  &#8220;<em><strong>No value accessor for form control with name: &#8216;country<\/strong> &#8230; <\/em>&#8220;<\/p>\n\n\n\n<p>That&#8217;s happens because <code>value accessor<\/code>\u00a0need to be implemented  first in custom component.\u00a0<em><span class=\"has-inline-color has-vivid-cyan-blue-color\">Control Value Accessor interface gives us the power to leverage the Angular forms API, and create a connection between it and the DOM element.<\/span><\/em><\/p>\n\n\n\n<p>Here are the STEPS: <\/p>\n\n\n\n<ol><li>Add the provider for <strong>NG_VALUE_ACCESSOR <\/strong>in the decorator<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code> import ...\n        import { Component, forwardRef } from '@angular\/core';\n        import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular\/forms';\n        \n    \n        @Component({\n\n            selector: 'custom-select',\n            templateUrl: 'custom-select.component.html',\n            styleUrls: &#91;'custom-select.component.css'],\n \/\/ STEP 1\n            providers: &#91;{\n              provide: NG_VALUE_ACCESSOR,\n              multi: true,\n              useExisting: forwardRef(() =&gt; CustomSelectComponent)\n            }]\n        })<\/code><\/pre>\n\n\n\n<p>2. Implement the ControlValueAccessor in the class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ STEP 2\n export class CustomSelectComponent implements ControlValueAccessor {\n        \/\/ write code here   .....\n }<\/code><\/pre>\n\n\n\n<p id=\"8296\">Now it\u2019s time to implement the ControlValueAccessor interface.<\/p>\n\n\n\n<p id=\"269e\">We\u2019re going to need to implement the following methods and variables:<\/p>\n\n\n\n<ul><li><strong>onChange\u00a0<\/strong>? the callback function to register on UI change<\/li><li><strong>onTouch\u00a0<\/strong>? the callback function to register on element touch<\/li><li><strong>set value(val: any)\u00a0<\/strong>? sets the value used by the ngModel of the element<\/li><li><strong>writeValue(value: any)\u00a0<\/strong>? This will write the value to the view if the the value changes occur on the model programmatically<\/li><li><strong>registerOnChange(fn: any)\u00a0<\/strong>? When the value in the UI is changed, this method will invoke a callback function<\/li><li><strong>registerOnTouch(fn: any)<\/strong>\u00a0? When the element is touched, this method will get called<\/li><\/ul>\n\n\n\n<p>3. Create the onChange function <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\nexport class CustomSelectComponent implements ControlValueAccessor {\n     ... write code here   .....\n \/\/ STEP 3 : onChange function\n   propagateChange = (_: any) =&gt; {\n};\n }<\/code><\/pre>\n\n\n\n<p>4. Add the registerOnChange, writeValue and registerOnTouched methods of the ControlValueAccessor interface<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class CustomSelectComponent implements ControlValueAccessor {\n     ... write code here   .....\n   \/\/onChange function\n   propagateChange = (_: any) =&gt; {\n};\n\n\n\/\/ STEP 4\n   registerOnChange(fn: (_: any) =&gt; void) {\n       this.propagateChange = fn;\n   }\n   writeValue() {}\n   registerOnTouched(){}\n }<\/code><\/pre>\n\n\n\n<p>5. In the method that will changed the value of select, call the onChange function passing as parameter the new-value of select.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\nexport class CustomSelectComponent implements ControlValueAccessor {\n        \/\/ write code here   .....\n\n\/\/ STEP 5\n   onSelectionChange(event: any) {\n       this.propagateChange(event.value);\n   }\n }\n\n<\/code><\/pre>\n\n\n\n<p>6.  Implement the  value setter &amp; writeValue Abstract function<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/STEP 6\n\nval= \"\" \/\/ this is the updated value that the class accesses. We can also use a formControl \/\/ for example in case of a custom selectBox,we could instead use \n\/\/selectCtrl: FormControl = new FormControl();\nset value(val:any){\n    if( val !== undefined &amp;&amp; this.val !== val){\n      this.val = val; \/\/ in case of selectBox: this.selectCtrl.setValue(val);\n      this.propagateChange(val)\n    }\n }\n\n\/\/ this method sets the value programmatically\nwriteValue(value: any){ \n  this.value = value; \/\/In case of selectBox: this.selectCtrl.setValue(value);\n}\n<\/code><\/pre>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p><\/p>\n\n\n\n<p>In the HTML :<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;div &#91;formGroup]=\"filterFormControls\"&gt;\n   &lt;custom-select &#91;items]=\"selectItems\" formControlName=\"country\"  \n     (change)=\"onSelectionChange($event)\"&gt;\n   &lt;\/custom-select&gt;\n&lt;\/div&gt;<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p><em><strong>Now, if we transpile the code again&#8230;everything will work fine. The formControlName ist binded in component. <\/strong><\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Let&#8217;s assume we create a custom (angular) Component &#8220;custom-select&#8221; in a reactive form and want to use it like below: If we yet try to transpile the code, we will get the following errors : &#8220;No value accessor for form control with name: &#8216;country &#8230; &#8220; That&#8217;s happens because value accessor\u00a0need to be implemented first [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1965,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37],"tags":[676,679,675,677,678],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2633"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=2633"}],"version-history":[{"count":3,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2633\/revisions"}],"predecessor-version":[{"id":2653,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2633\/revisions\/2653"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1965"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=2633"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=2633"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=2633"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}