[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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-11-01 [Angular 2] Pipes with Multiple Parameters
2015-11-01 [Angular 2] Create a simple search Pipe
2015-11-01 [Angular 2] Pipe Purity
2015-11-01 [Angular 2] Exposing component properties to the template
2015-11-01 [Angular 2] ng-model and ng-for with Select and Option elements