11import { Component , ElementRef , Input , Optional , Self } from "@angular/core" ;
22import {
33 FormControl ,
4+ FormControlDirective ,
45 FormGroup ,
56 FormGroupDirective ,
67 NgControl ,
78 NgForm ,
89 ReactiveFormsModule ,
10+ ValidationErrors ,
11+ ValidatorFn ,
912} from "@angular/forms" ;
1013import { ErrorStateMatcher } from "@angular/material/core" ;
1114import { MatFormFieldControl } from "@angular/material/form-field" ;
@@ -27,6 +30,7 @@ export class RangeInputComponent extends CustomFormControlDirective<NumericRange
2730 from : new FormControl ( ) ,
2831 to : new FormControl ( ) ,
2932 } ) ;
33+ formControlDirective : FormControlDirective ;
3034
3135 @Input ( ) set value ( value : NumericRange ) {
3236 // update the internal formGroup when the value changes from the outside
@@ -37,12 +41,16 @@ export class RangeInputComponent extends CustomFormControlDirective<NumericRange
3741 return super . value ;
3842 }
3943
44+ @Input ( )
45+ deactivateValidation : boolean = false ;
46+
4047 constructor (
4148 elementRef : ElementRef < HTMLElement > ,
4249 errorStateMatcher : ErrorStateMatcher ,
4350 @Optional ( ) @Self ( ) ngControl : NgControl ,
4451 @Optional ( ) parentForm : NgForm ,
4552 @Optional ( ) parentFormGroup : FormGroupDirective ,
53+ @Optional ( ) formControlDirective : FormControlDirective ,
4654 ) {
4755 super (
4856 elementRef ,
@@ -52,11 +60,27 @@ export class RangeInputComponent extends CustomFormControlDirective<NumericRange
5260 parentFormGroup ,
5361 ) ;
5462
63+ this . formControlDirective = formControlDirective ;
5564 this . formGroup . valueChanges . subscribe ( ( value ) => {
5665 this . value = value ;
57- console . log ( "internal value changes" , this . value ) ;
5866 } ) ;
5967 }
68+
69+ private validatorFunction : ValidatorFn = ( ) : ValidationErrors | null => {
70+ if ( this . value . from && this . value . to && this . value . from > this . value . to ) {
71+ return {
72+ fromGreaterThanTo : "The from value is greater than the to value." ,
73+ } ;
74+ } else {
75+ return null ;
76+ }
77+ } ;
78+
79+ ngAfterViewInit ( ) {
80+ if ( ! this . deactivateValidation ) {
81+ this . formControlDirective . form . addValidators ( [ this . validatorFunction ] ) ;
82+ }
83+ }
6084}
6185
6286export class NumericRange {
0 commit comments