//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的更多相关文章

  1. [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 ...

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

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

  3. 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 ...

  4. 关于Form.Close跟Form.Dispose

    我们在Winform开发的时候,使用From.Show来显示窗口,使用Form.Close来关闭窗口.熟悉Winform开发的想必对这些非常熟悉.但是Form类型实现了IDisposable接口,那我 ...

  5. Form.Close跟Form.Dispose

    关于Form.Close跟Form.Dispose   我们在Winform开发的时候,使用From.Show来显示窗口,使用Form.Close来关闭窗口.熟悉Winform开发的想必对这些非常熟悉 ...

  6. How to: Create Custom Configuration Sections Using ConfigurationSection

    https://msdn.microsoft.com/en-us/library/2tw134k3.aspx You can extend ASP.NET configuration settings ...

  7. [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. ...

  8. UE4 Tutorial - Custom Mesh Component 用于绘制自定义网格的插件CustomMeshComponent

    UE4 中用于绘制自定义网格的插件CustomMeshComponent. 转载: UE4 Tutorial - Custom Mesh Component   Over the last few w ...

  9. day75 form 组件(对form表单进行输入值校验的一种方式)

    我们的组件是什么呢 select distinct(id,title,price) from book ORM: model.py class Book(): title=model.CharFiel ...

随机推荐

  1. 2017国家集训队作业[arc076d/f][Exhausted?]

    2017国家集训队作业[arc076d/f][Exhausted?] 题意: ​ 有\(N\)个人,\(M\)把椅子,给出\(...L_i.R_i\)表示第\(i\)个人可以选择编号为\(1\sim ...

  2. python之-字符编码

    1.内存和硬盘都是用来存储的. CPU:速度快 硬盘:永久保存 2.文本编辑器存取文件的原理(nodepad++,pycharm,word) 打开编辑器就可以启动一个进程,是在内存中的,所以在编辑器编 ...

  3. 【Codeforces Round #427 (Div. 2) C】Star sky

    [Link]:http://codeforces.com/contest/835/problem/C [Description] 给你n个星星的坐标(xi,yi); 第i个星星在第t秒,闪烁值变为(s ...

  4. PatentTips - Improving security in a virtual machine host

    BACKGROUND Computer viruses are a common problem for computer users. One typical mode of attack is t ...

  5. NB大了,增强现实走进安防行业了!竟然还有智能家居的规划!

     增强现实系统故事性功能解说 作者:李欢   工号:2288  电话:18938902295 邮箱:lihuan@gosuncn.com 前言: 本文仅适用于2014北京安防展,增强现实展区人员学 ...

  6. 兔子--ps中的基本工具总结(ps cs5)

    矩形选框工具 椭圆选框工具 单行选框工具 单列选框工具 移动工具 套索工具柜 多边形套索工具 磁性套索工具 魔棒工具 高速选择工具 裁剪工具 切片工具 切片选择工具 吸管工具 颜色取样器工具 标尺工具 ...

  7. excel表如何实现多if选择结构多分支判断

    excel表如何实现多if选择结构多分支判断 一.总结 一句话总结:把多if分支转换成单if分支相加. 也可以if分支,也可以lookup函数. 1.CHOICE: +2 if band A; +1 ...

  8. Servlet简单注解方式使用

    我们是用Servlet进行跳转的时候都需要去web.xml中进行配置,分繁琐. 那么今天就学习下使用注解方式配置servlet一样好使 package com.shxt.servlet; import ...

  9. 如何应对DDOS网络攻击

      650) this.width=650;" border="0" alt="" src="http://img1.51cto.com/a ...

  10. 洛谷 P2692 覆盖

    P2692 覆盖 题目背景 WSR的学校有B个男生和G个女生都来到一个巨大的操场上扫地. 题目描述 操场可以看成是N 行M 列的方格矩阵,如下图(1)是一个4 行5 列的方格矩阵.每个男生负责打扫一些 ...