So when you need to create a ControlValueAccessor?

When you want to use a custom component as form control. For example a counter component, you can custom the style and the way to control the value changes.

It needs some setup for control value accessor, but after you have done it once, you can prettty much just copy & paste the same template around to create a control value access.

import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; const COUNTER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => StockCounterComponent),
multi: true
}; @Component({
selector: 'stock-counter',
providers: [COUNTER_VALUE_ACCESSOR],
styleUrls: ['stock-counter.component.scss'],
template: `
...
`
})
export class StockCounterComponent implements ControlValueAccessor { value: number; writeValue(val: number) {
this.value = val;
} registerOnChange(fn: any) {
this.onModelChange = fn;
} registerOnTouched(fn: any) {
this.onTouch = fn;
} ...
}

So the template is somehow like the code above, highly recommend to create any snippet or live template in your IDE.

So inside the component we create, we have three methods,

  • writeValue(obj: any)
  • registerOnChange(fn: Function)
  • registerOnTouched(fn: Function)

To understand each method is the key point to understand how control value access.

So first 'writeValue':

  value: number;

  writeValue(val: number) {
this.value = val;
}

This is for setting initial value, we take value from our form builder and pass to our component via 'writeValue'.

        <stock-counter
[step]=""
[min]=""
[max]=""
formControlName="quantity">

So the value comes from 'formControlName="quantity"'.

Now at the point, you can think that our form holds a model value and our component also holds a view value.

We need to sync model value and view value.

The way to do that is by "registerOnChange":

  registerOnChange(fn: any) {
this.onModelChange = fn;
}
  increment() {
this.value = this.value === this.max ?
this.value :
this.value + this.step; this.onModelChange(this.value); }

Every time our view value (component value) changed, to need to notify our form about the changes, we need to call 'this.onModelChange(this.value)' function and pass in the changes value.

After this form will be able to the updated value.

OK, now we able to sync the value from our component to our form. But you might think about this can be easily done by EventEmitter, when border to create Control value accessor? The most important reason is that "Validation"!

html "form" component actually does lots of thing underhook. What example, it set field state "untouch", "touched", "dirty", "prinstin". We use those status to do validation and error messages.

For example:

input.ng-touched.ng-invalid {
border-left: 5px solid red;
}

If the field is touched and is invalid, we set the border to red.

Currently, we have our value synced, and control value access also helps us to add form validation ability to our component. But once the value changed, our component still show 'ng-untouch':

So we need "registerOnTouched" function to help us to do that:

  registerOnTouched(fn: any) {
this.onTouch = fn;
}
  increment() {
this.value = this.value === this.max ?
this.value :
this.value + this.step; this.onModelChange(this.value);
this.onTouch();
}

Now after the value changed, our component will be set 'ng-touched', now we are fully conver our component to a form component.

Code

[Angular] Implementing a ControlValueAccessor的更多相关文章

  1. [Angular] Implementing A General Communication Mechanism For Directive Interaction

    We have modal implement and now we want to implement close functionality. Becuase we use a structure ...

  2. [Angular] Create a ng-true-value and ng-false-value in Angular by controlValueAccessor

    If you're coming from AngularJS (v1.x) you probably remember the ng-true-value and ng-false-value di ...

  3. Angular写一个Form组件-TagInput

    前端开发少不了和表单打交道; Angular中, 提供了强大的表单的支持, 响应式表单(Reactive Form) 和 模板驱动的表单(Template-driven Form) 的双向数据流给我们 ...

  4. Angular Forms - 自定义 ngModel 绑定值的方式

    在 Angular 应用中,我们有两种方式来实现表单绑定--"模板驱动表单"与"响应式表单".这两种方式通常能够很好的处理大部分的情况,但是对于一些特殊的表单控 ...

  5. angular实现简单的pagination分页组件

    不想使用第三方库,只想使用一个分页器,那么就简单的实现一个,效果如下: 1.使用方式: <custom-pagination *ngIf="enterpriseList.length& ...

  6. [AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor

    The upload class will be used in the service layer. Notice it has a constructor for file attribute, ...

  7. [Angular] Implement a custom form component by using control value accessor

    We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...

  8. angular 响应式自定义表单控件—注册头像实例

    1. 组件继承ControlValueAccessor,ControlValueAccessor接口需要实现三个必选方法 writeValue() 用于向元素中写入值,获取表单的元素的元素值 regi ...

  9. 表单-angular

    模板表单: <form #myform="ngForm" (ngSubmit)="onsubmit(myform.value)" > <div ...

随机推荐

  1. Shell中反引号(`)与$()用法的区别

    今天有人提问: echo `echo \\\\\\\w` echo $(echo \\\\\\\w) 为什么输出的不一样? 这就引申出了另一个问题:反引号与$()有没有区别? 这是一个非常有意思的问题 ...

  2. 使用solr的DIHandler 构建mysql大表全量索引,内存溢出问题的解决方法

    solr官方给出的解决方式是: DataImportHandler is designed to stream row one-by-one. It passes a fetch size value ...

  3. 软件——protel 的pcb电路图制作

    近期一直在学习PCB板的绘制.

  4. Flask项目之手机端租房网站的实战开发(四)

    说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 接着上一篇博客继续往下写 :https://blog.csdn.net/qq_41782425/article/details/8 ...

  5. 使用jmeter监控服务器性能指标

    先下载jmeter-ServerAgent Windows下载和Linux下载 https://jmeter-plugins.org/wiki/PerfMon/  找到ServerAgent的下载链接 ...

  6. spring mvc笔记

    80214shuenjian224shuenjian@sina 北风网公开课课程大纲1.学习MVC框架的步骤2.Spring MVC运行机制3.演示Spring MVCAdd Maven suppor ...

  7. 00091_字符输入流Reader

    1.字符输入流Reader (1)字符输入流Reader我们读取拥有中文的文件时,使用的字节流在读取,那么我们读取到的都是一个一个字节: (2)只要把这些字节去查阅对应的编码表,就能够得到与之对应的字 ...

  8. 机房收费 &amp; 廊院食堂

    做机房收费系统时.常常想这个一般用户指的是谁?我当初以为是学生......可能是被数据库中的student带跑偏了...... 事实上把我们的系统联系一下实际,就会非常easy想到一般用户指的是谁的位 ...

  9. 软件——keil的查找,错误,不能跳转到相应的行

    为什么MDK  keil4.7双击搜索结果不能跳转到相应位置 KEIL搜索的时候双击不跳转到相应的位置 为什么keil点击不能跳转到错误处的问题 在keil中,双击Find In Files中某一行, ...

  10. IOS上架App Store商店步骤

    苹果官方在2015年05-06月开发者中心进行了改版,网上的APP Store上架大部分都不一样了,自己研究总结一下,一个最新的上架教程以备后用. 原文地址:http://www.16css.com/ ...