//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. HDU 1576 A/B 数论水题

    http://acm.hdu.edu.cn/showproblem.php?pid=1576 写了个ex_gcd的模板...太蠢导致推了很久的公式 这里推导一下: 因为 1 = BX + 9973Y ...

  2. ZJU 2425 Inversion

    Inversion Time Limit: 2000ms Memory Limit: 65536KB This problem will be judged on ZJU. Original ID:  ...

  3. libssh2进行远程运行LINUX命令

    /** * CSSHClient.h * @file 说明信息.. * DATE February 13 2015 * * @author Ming_zhang */ #ifndef _CSSHCLI ...

  4. BZOJ 1696 [Usaco2007 Feb]Building A New Barn新牛舍 数学

    题意:链接 方法:数学+模拟 解析: 首先这类问题不是第一次见了,所以直接知道拿x的中位数.y的中位数. 这题就是讨论情况很的烦. 题中有个限制,给出待求和的点不能选取. 所以假设奇数个点,求出x中位 ...

  5. 33.promise future多线程通信

    #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <thread> #include <futur ...

  6. jQuery UI:邮箱自动补全函数

    $('#email').autocomplete({ delay:0, autoFocus:true, source:function(request,response){ var hosts = [ ...

  7. Objective-C基础笔记(1)基本概念和第一个程序

    一.基本概念 Objective-C(简称OC)是iOS开发的核心语言,苹果公司在维护,在开发过程中也会配合着使用C语言.C++,OC主要负责UI界面,C语言.C++可用于图形处理.C语言是面向过程的 ...

  8. 随时查看源码的网站---http://www.sooset.com/

    由于工作需要经常要在Windows平台下参阅linux源码,以前都用http://lxr.linux.no/来浏览源码(如下图所示),最近发现sooset来浏览更方便,所以介绍给大家分享. 650) ...

  9. org.omg.CORBA.MARSHAL: vmcid: SUN minor code: 211 completed: Maybe

    用weblogic 12c 测试 ejb3 import javax.naming.InitialContext; import javax.naming.NamingException; impor ...

  10. 7.Linux 输入子系统分析

    为什么要引入输入子系统? 在前面我们写了一些简单的字符设备的驱动程序,我们是怎么样打开一个设备并操作的呢? 一般都是在执行应用程序时,open一个特定的设备文件,如:/dev/buttons .... ...