[Angular] Implementing a ControlValueAccessor
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.
[Angular] Implementing a ControlValueAccessor的更多相关文章
- [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 ...
- [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 ...
- Angular写一个Form组件-TagInput
前端开发少不了和表单打交道; Angular中, 提供了强大的表单的支持, 响应式表单(Reactive Form) 和 模板驱动的表单(Template-driven Form) 的双向数据流给我们 ...
- Angular Forms - 自定义 ngModel 绑定值的方式
在 Angular 应用中,我们有两种方式来实现表单绑定--"模板驱动表单"与"响应式表单".这两种方式通常能够很好的处理大部分的情况,但是对于一些特殊的表单控 ...
- angular实现简单的pagination分页组件
不想使用第三方库,只想使用一个分页器,那么就简单的实现一个,效果如下: 1.使用方式: <custom-pagination *ngIf="enterpriseList.length& ...
- [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, ...
- [Angular] Implement a custom form component by using control value accessor
We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...
- angular 响应式自定义表单控件—注册头像实例
1. 组件继承ControlValueAccessor,ControlValueAccessor接口需要实现三个必选方法 writeValue() 用于向元素中写入值,获取表单的元素的元素值 regi ...
- 表单-angular
模板表单: <form #myform="ngForm" (ngSubmit)="onsubmit(myform.value)" > <div ...
随机推荐
- BZOJ2716: [Violet 3]天使玩偶(KD-Tree)
Description Input Output Sample Input 100 100 81 23 27 16 52 58 44 24 25 95 34 2 96 25 8 14 97 50 97 ...
- 字符设备驱动-------Linux异常处理体系结构
裸机中断流程 外部触发 CPU 发生中断, 强制的跳到异常向量处 跳转到具体函数 保存被中断处的现场(各种寄存器的值) 执行中断处理函数,处理具体任务 恢复被中断的现场 Linux处理异常流程 异常发 ...
- Hadoop学习总结(2)——Hadoop入门详解
1.Hadoop介绍 Hadoop是Apache软件基金会旗下的一个开源分布式计算平台,为用户提供了一个系统底层细节透明的分布式架构,通过Hadoop,可以将大量的廉价机器的计算资源组织起来,解决单机 ...
- oracle学习之路(二)------数组类型/记录类型的使用
Oracle记录类型介绍 RECORD:用户自己定义数据类型,由单行多列的标量构成的复合数据类型.它将一个或多个标量封装成一个对象进行操作记录不能够总体拿来比較也不能够总体推断为空.能够总体拿来赋值. ...
- HDU 4927 Series 1(推理+大数)
HDU 4927 Series 1 题目链接 题意:给定一个序列,要求不断求差值序列.直到剩一个,输出这个数字 思路:因为有高精度一步.所以要推理一下公式,事实上纸上模拟一下非常easy推出公式就是一 ...
- VPS 的 CentOS6 升级 Python 的方法
VPS 的 CentOS6 升级 Python 的方法 centos默认安装python2.6.由于python和centos关联紧密,所以不建议卸载,进行编译升级 1.新开的VPS务必系统更新 yu ...
- 课程与教学管理系统(CMS):Sakai
课程与教学管理系统(CMS):Sakai 一.总结 java的spring.Hibernate等框架开发的 J2EE的开源cms 二.SAKAI Sakai是一个自由.开源的在线协作和学习环境,由Sa ...
- 为什么选择Solr?
在大型的SQL数据库上很难执行高速的查询有Solr是Apache 下的一个开源项目,使用Java基于Lucene开发的全文检索服务: 它是一个独立的企业级搜索应用服务器,它对外提供类似于Web-ser ...
- Android Studio com.android.dex.DexException: Multiple dex files define(重复引用包)
如果你用Android Studio开发,并且要用其他项目作为library,这个问题是很容易出现的.出现这个问题的原因是包的重复引用,意思就是在你自己的项目中引用了某个包,而被你作为library的 ...
- GO语言学习(十八)Go 语言接口
Go 语言接口 Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口. 实例 /* 定义接口 */ type interface ...