//Switch-control ComponentImport {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}]}) ExportclassSwitchcontrolcomponent 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 your use ngmodel to bind your control to data.
The Registeronchange accepts a callback function which you can call when changes happen so this you can notify th E outside world and the data model has changed. Note that this is the 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 T o touched. This was then managed by Angular 2 by adding the correct touched state and classes to the actual element tag in th E DOM.
Using it:
this. Signupform = fb.group ({ password: [ ', validators.required ] , confirm: [ ', ', [ validators.required ,this . Signup) ] ], true });
<formnovalidate AutoComplete= "Off"[Formgroup]= "Signupform"> <Divclass= "Form-field"> <label>Password:</label> <inputtype= "text"Formcontrolname= "Password"[(Ngmodel)]= "Signup.password"name= "Password"> </Div> <Divclass= "Form-field"> <label>Confirm Password:</label> <inputtype= "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 with the code we set the default value to being true thought "WriteValue" method handle by Angular2, also we get updated V Alue 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