forms - Setting the validity of a Angular 2 control from within a custom component -


i have custom ng2 component using model-driven approach.

<form [ngformmodel]="myform" class="layout vertical relative">     <my-custom-comp ngcontrol="currentvalue"></my-custom-comp> </form> 

so inside custom component have logic need can't find way reference ngcontrol set valid or invalid inside custom component.

you can check link working example: https://github.com/byavv/angular2-playground/tree/master/client/app/modules/forms_explore

some key aspects:
need implement controvalueaccessor.

export class datepicker implements controlvalueaccessor { 

inject in component ngcontrol , register it:

constructor(private ngcontrol:ngcontrol) ngcontrol.valueaccessor = this; 

from within component should have form validates field can subscribe emit correct value or set error of parent ngcontrol form.

 this.dateform = builder.group({           datecontrol: ['', validators.compose([validators.required, customvalidators.frenchdate])],         });      this.dateform.valuechanges       .subscribe((val) => {         if (this.dateform.valid) {           this.onchange.emit(this.datetotimestamp(val.datecontrol));         } else {           this.ngcontrol.control.seterrors({ "wrongdate": true });         }       });