[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 ...
随机推荐
- 【Codeforces Round #455 (Div. 2) B】Segments
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 处理出所有的线 其实就是区间. 总共有n*(n+1)/2个 然后按照左端点.右端点排序 每次取最左边的线. 多种可能就取右端点尽量小 ...
- Android 调试出现 could not get wglGetExtensionsStringARB
解决 AVD Manager -> 选择模拟器 -> 点击 Edit看 Enabled 是不是被选中了.是的话取消选中,OK.希望对你实用.
- 开发板 Linux驱动视频 驱动是什么
内存管理单元很重要. linux把设备看成文件,(open,read,write,ioctrl,close)主要写这几个函数. 哈弗结构,取指令和取数据同时进行. arm处理器体系架构以及发展方向 单 ...
- Python 极简教程(十二)逻辑控制语句 if else
计算机软件之所以能够对不同的情况进行不同的处理,就是我们在编码的时候,通过逻辑控制语句,告诉软件在不同的情况下应该做什么处理. 比如我们在登录的时候,那么当你输入正确的账号密码和错误的账号密码,完全是 ...
- 【2017 Multi-University Training Contest - Team 10】Schedule
[链接]http://acm.hdu.edu.cn/contests/contest_showproblem.php?pid=1010&cid=767 [题意] 给一些区间,每台机器在这些区间 ...
- Hbase技术详细学习笔记
注:转自 Hbase技术详细学习笔记 最近在逐步跟进Hbase的相关工作,由于之前对Hbase并不怎么了解,因此系统地学习了下Hbase,为了加深对Hbase的理解,对相关知识点做了笔记,并在组内进行 ...
- cocos2d-x 3.0 游戏关卡滑动 弹动 不会出现黑边效果
#pragma once #include "cocos2d.h" #include "ShopScene.h" using namespace cocos2d ...
- centos7 分区满了,分析哪个目录或文件占用空间-小叶-51CTO博客
原文:centos7 分区满了,分析哪个目录或文件占用空间-小叶-51CTO博客 du -sh 例如: [root@zabbix ~]# du -sh /var/* 0 /var/adm 132M / ...
- [React Intl] Use a react-intl Higher Order Component to format messages
In some cases, you might need to pass a string from your intl messages.js file as a prop to a compon ...
- MongoDbHelper 帮助类(上)
在网上搜索mongodbHelper的帮助类时,出来的东西都大同小异,再此摘录一下. 这些代码也看了一遍,总是感觉重复的代码太多了,在后续的文章中又整合了一下,请看下篇,欢迎指正! using Sys ...