[Angular2 Form] Create custom form component using Control Value Accessor
//switch-control component import { Component } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators} from '@angular/forms'; @Component({
selector: 'switch-control',
templateUrl: './switch-control.component.html',
styleUrls: ['./switch-control.component.css'],
providers: [
{provide: NG_VALUE_ACCESSOR, multi: true, useExisting: SwitchControlComponent}
]
})
export class SwitchControlComponent implements ControlValueAccessor {
isOn: boolean;
_onChange: (value: any) => void; writeValue(value: any) {
this.isOn = !!value;
} registerOnChange(fn: (value: any) => void) {
this._onChange = fn;
} registerOnTouched() {} toggle(isOn: boolean) {
this.isOn = isOn;
this._onChange(isOn);
}
}
The writeValue function allows you to update your internal model with incoming values, for example if you use ngModel to bind your control to data.
The registerOnChange accepts a callback function which you can call when changes happen so that you can notify the outside world that the data model has changed. Note that you call it with the changed data model value.
The registerOnTouched function accepts a callback function which you can call when you want to set your control to touched. This is then managed by Angular 2 by adding the correct touched state and classes to the actual element tag in the DOM.
Using it:
this.signupForm = fb.group({
password: [
'',
Validators.required
],
confirm: [
'',
[
Validators.required,
confirmPasswords.bind(undefined, this.signup)
]
],
newsletter: true
});
<form novalidate autocomplete="off" [formGroup]="signupForm">
<div class="form-field">
<label>Password:</label>
<input type="text" formControlName="password" [(ngModel)]="signup.password" name="password">
</div>
<div class="form-field">
<label>Confirm Password: </label>
<input type="text" formControlName="confirm" [(ngModel)]="signup.confirm" name="confrim">
<div *ngIf="!signupForm.valid">
<span *ngIf="signupForm.get('confirm').hasError('confirmPassword') && signupForm.get('confirm').touched">
{{signupForm.get('confirm').errors?.confirmPassword.message}}
</span>
<span *ngIf="signupForm.get('confirm').hasError('required') && signupForm.get('confirm').dirty">This field is requred</span>
</div>
<switch-control formControlName="newsletter"></switch-control>
</div>
</form>
Here in the code we set the default value to be true thought "writeValue" method handle by angular2, also we get updated value from the component thought "registonChange" method.
Link: http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel
Github: https://github.com/kara/ac-forms/tree/master/src/app/switch-control
[Angular2 Form] Create custom form component using Control Value Accessor的更多相关文章
- [Angular2 Form] Model Driven Form Custom Validator
In this tutorial we are going to learn how simple it is to create custom form field driven validator ...
- [Angular] Implement a custom form component by using control value accessor
We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...
- Receive Windows Messages In Your Custom Delphi Class - NonWindowed Control - AllocateHWnd
http://delphi.about.com/od/windowsshellapi/a/receive-windows-messages-in-custom-delphi-class-nonwind ...
- 关于Form.Close跟Form.Dispose
我们在Winform开发的时候,使用From.Show来显示窗口,使用Form.Close来关闭窗口.熟悉Winform开发的想必对这些非常熟悉.但是Form类型实现了IDisposable接口,那我 ...
- Form.Close跟Form.Dispose
关于Form.Close跟Form.Dispose 我们在Winform开发的时候,使用From.Show来显示窗口,使用Form.Close来关闭窗口.熟悉Winform开发的想必对这些非常熟悉 ...
- How to: Create Custom Configuration Sections Using ConfigurationSection
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx You can extend ASP.NET configuration settings ...
- [Angular] Adding keyboard events to our control value accessor component
One of the most important thing when building custom form component is adding accessbility support. ...
- UE4 Tutorial - Custom Mesh Component 用于绘制自定义网格的插件CustomMeshComponent
UE4 中用于绘制自定义网格的插件CustomMeshComponent. 转载: UE4 Tutorial - Custom Mesh Component Over the last few w ...
- day75 form 组件(对form表单进行输入值校验的一种方式)
我们的组件是什么呢 select distinct(id,title,price) from book ORM: model.py class Book(): title=model.CharFiel ...
随机推荐
- 今日 SGU 5.6
SGU 106 题意:问你有多少个<x,y>,满足ax+by+c=0,x1<=x<=x2,y1<=y<=y2 收货:拓展欧几里得求解的是这种方程,ax+by=1,g ...
- zenDiscovery和master选举
上一篇通过 ElectMasterService源码,分析了master选举的原理的大部分内容:master候选节点ID排序保证选举一致性及通过设置最小可见候选节点数目避免brain split.节点 ...
- while 循环的理解
if 与 while 的主要区别:if 只判断和执行一次,而 while 却代表着一个循环,执行多少次,要视情况而定: 两种情况(A.B)都会让循环体执行: while A or B: 两种情况(A. ...
- Apache通用日志工具commons-logging和Log4j使用总结
转自:https://blog.csdn.net/lzl13391522110/article/details/53758536 Apache通用日志工具commons-logging和Log4j使用 ...
- java根据url获取完整域名
private String getDomain(String destination){ if(destination==null||destination.trim().equals(" ...
- element-UI 表单校验失效处理
1.el-form-item 的 prop属性绑定的要是字符串: eg: :prop="'answer[' + 0 + ']' " //而不是 :prop=&qu ...
- C# 中 int、Convert.ToInt32()、int.Parse()的区别
int适合简单数据类型之间的转换,C#的默认整型是int32(不支持bool型); int.Parse(string sParameter)是个构造函数,参数类型只支持string类型; Conver ...
- Codeforces 451 E. Devu and Flowers(组合数学,数论,容斥原理)
传送门 解题思路: 假如只有 s 束花束并且不考虑 f ,那么根据隔板法的可重复的情况时,这里的答案就是 假如说只有一个 f 受到限制,其不合法时一定是取了超过 f 的花束 那么根据组合数,我们仍然可 ...
- CISP/CISA 每日一题 18
CISSP 每日一题(答)What is the purpose of an access review and audit? Checkto ensure that users do not hav ...
- hdu-3642--Get The Treasury-线段树求面积并
求空间中叠加3次及3次以上的体积. 由于|z|<=500.所以直接把z轴剥离出来1000层. 然后对于每一层进行线段树求面积并. #include<stdio.h> #include ...