//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. linux 下find---xargs以及find--- -exec结合使用

    例:删除/home/raven下,包括子目录里所有名为abc.txt的文件: find /home/raven -name abc.txt | xargs rm -rf 如果不使用xargs,则为: ...

  2. [置顶] Docker学习总结(1)——Docker实战之入门以及Dockerfile(一)

    一.Docker是什么? 首先Docker是软件工业上的集装箱技术 回顾,在没有集装箱出现以前,传统运输行业中,会存在这些问题: 在运输过程中,货物损坏 装卸.运输货物,效率低下 运输手续繁多及运输环 ...

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

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

  4. 【LeetCode-面试算法经典-Java实现】【130-Surrounded Regions(围绕区域)】

    [130-Surrounded Regions(围绕区域)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a 2D board containing 'X ...

  5. 洛谷P1316 丢瓶盖

    题目描述 陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢? 输入输出 ...

  6. c#的中英文混合字符串截取 public static string SubString(string inputString, int byteLength)

    /// <summary>        /// c#的中英文混合字符串截取(区分中英文)        /// </summary>        /// <param ...

  7. Vue 消息无缝滚动

    vue实现消息向上无缝滚动效果 <ul class="new-list" :class="{anim:animate}" @mouseenter=&quo ...

  8. Spring学习总结(6)——Spring之核心容器bean

    一.Bean的基础知识 1.在xml配置文件中,bean的标识(id 和 name) id:指定在benafactory中管理该bean的唯一的标识.name可用来唯一标识bean 或给bean起别名 ...

  9. 洛谷——P1073 最优贸易 ([NOIP2009] )

    https://www.luogu.org/problem/show?pid=1073 题目描述 C 国有 n 个大城市和 m 条道路,每条道路连接这 n 个城市中的某两个城市.任意两个 城市之间最多 ...

  10. php线性表数组实现的删除操作

    php线性表数组实现的删除操作 一.总结 1.array_pop(): 函数删除数组中的最后一个元素. 二.代码 代码一: //线性表的删除(数组实现) function delete_array_e ...