[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 ...
随机推荐
- java(面向对象 )
java面向对象的语言 对象:真实存在唯一的事物. 类:实际就是对某种类型事物的共性属性与行为的抽取. 面向对象的计算机语言核心思想: 找适合的对象做适合的事情. 如何找适合的对象: 1.sun已经定 ...
- 「HAOI2018」字串覆盖
「HAOI2018」字串覆盖 题意: 给你两个字符串,长度都为\(N\),以及一个参数\(K\),有\(M\)个询问,每次给你一个\(B\)串的一个子串,问用这个字串去覆盖\(A\)串一段区间的最 ...
- RGB 颜色空间转 HSI 颜色空间的matlab程序实现
RGB 颜色空间转 HSI 颜色空间的matlab程序实现 2014.10.20之前的内容有误,这里依据wikipedia更新了算法内容. 算法以wiki为准 https://en.wikipedia ...
- IAR FOR STM8 学习笔记 IAR工程的建立
STM8是ST意法半导体针对工业应用和消费电子开发而推出的8位单片机. 每种MCU都有自身的优点与缺点,与其它8-bit MCU相比,STM8 8-bit MCU最大的特点是: · 内核: o 最高f ...
- Java学习笔记四
1.简介.进程和线程:简单的说就是进程负责为程序开辟内存空间,线程负责具体的执行单元(执行路径). 一个进程中可以有多个执行路径,称为多线程.CPU一次只能执行一个进程,但是一个进程内部可以有多个线程 ...
- Echarts Y轴min显示奇葩问题(做此记录)
项目需求是根据不同情况显示最大值最小值 有9-35 12-50 9-50 三种情况 前面两种可以显示出来 但是9-50的话 最小值9显示不出来 8,7等就可以显示出来 后面想到强制从最小值 ...
- Linux文本编辑器
1.编辑模式 2.命令模式 3.底部命令模式 注意:如果发现编辑不了.可能是因为非法退出产生一个后缀名为.swp 的临时隐藏文件. 将其删除重新编辑即可!
- Appium_pytest fixture的使用
一.定义fixture方法 # -*- coding:utf-8 -*-import pytestfrom baseutil.DriverUtil import DriverConfig @pytes ...
- 【代码】Django学习笔记
一些设置setting.py DEBUG = True ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.ba ...
- 读书笔记-Java设计模式
本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! Java的封装性很好,拿访问控制符来讲,没有权限的类或方法是不能访问的.如public,都可访问:p ...