//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. 新版mysql修改root密码

  2. 【习题 8-11 UVA - 1615】Highway

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每个村庄都有一个范围[li..ri] 只要在这个范围内放点都可以"支配"这个村庄. 则问题就等价于线段上有n个区 ...

  3. mysql判断一个字符串是否包含某子串 【转】

    文章出处:mysql判断一个字符串是否包含某子串 使用locate(substr,str)函数,如果包含,返回>0的数,否则返回0 例子:判断site表中的url是否包含'http://'子串, ...

  4. ios学习之旅---c语言函数

    1.函数的概述 C源程序是由函数组成的. 尽管在前面各章的程序中大都仅仅有一个主函数main(),但有用程序往往由多个 函数组成. 函数是C源程序的基本模块,通过对函数模块的调用实现特定的功能. C语 ...

  5. MySQL具体解释(13)------------事务

    一. 什么是事务 事务就是一段sql 语句的批处理.可是这个批处理是一个atom(原子) .不可切割,要么都运行,要么回滚(rollback)都不运行. 二.为什么出现这样的技术 为什么要使用事务这个 ...

  6. JavaScript作用域闭包(你不知道的JavaScript)

    JavaScript闭包.是JS开发project师必须深入了解的知识. 3月份自己曾撰写博客<JavaScript闭包>.博客中仅仅是简单阐述了闭包的工作过程和列举了几个演示样例,并没有 ...

  7. 【hdu 3478】Catch

    [Link]:http://acm.hdu.edu.cn/showproblem.php?pid=3478 [Description] 一个人从起点s出发,假设他在时间t在节点x; 则在时间t+1,他 ...

  8. 设计模式六大原则(六): 开闭原则(Open Closed Principle)

    定义: 一个软件实体如类.模块和函数应该对扩展开放,对修改关闭. 问题由来: 在软件的生命周期内,因为变化.升级和维护等原因需要对软件原有代码进行修改时,可能会给旧代码中引入错误,也可能会使我们不得不 ...

  9. Mongodb总结4-Spring环境使用Mongodb

    前几次的例子,要么是Shell,要么是普通Java应用程序的例子.实际情况,是要在Spring的项目里用,因此需要做一些改造. 1.配置文件C:\hanhai\config\mongodb.prope ...

  10. Lucy_Hedgehog techniques

    在project euler 的第\(10\)题的 \(forum\) 中 Lucy Hedgehog 提到的这种方法. 求 \(n\) 以内素数个数以及求 \(n\) 以内素数和的算法. 定义\(S ...