|
| 1 | +import { ChangeDetectorRef, Directive, ElementRef, Inject, forwardRef } from '@angular/core'; |
| 2 | +import { NG_VALIDATORS, NG_VALUE_ACCESSOR, type ValidationErrors } from '@angular/forms'; |
| 3 | +import { type NumberField } from '@sl-design-system/number-field'; |
| 4 | +import { FormControlElementDirective } from './form-control-element.directive'; |
| 5 | + |
| 6 | +@Directive({ |
| 7 | + selector: 'sl-number-field', |
| 8 | + standalone: true, |
| 9 | + providers: [ |
| 10 | + { |
| 11 | + provide: NG_VALUE_ACCESSOR, |
| 12 | + useExisting: forwardRef(() => NumberFieldDirective), |
| 13 | + multi: true |
| 14 | + }, |
| 15 | + { |
| 16 | + provide: NG_VALIDATORS, |
| 17 | + useExisting: forwardRef(() => NumberFieldDirective), |
| 18 | + multi: true |
| 19 | + } |
| 20 | + ] |
| 21 | +}) |
| 22 | +export class NumberFieldDirective extends FormControlElementDirective<NumberField> { |
| 23 | + constructor( |
| 24 | + @Inject(ElementRef) elementRef: ElementRef<NumberField>, |
| 25 | + @Inject(ChangeDetectorRef) changeDetection: ChangeDetectorRef |
| 26 | + ) { |
| 27 | + super(elementRef, changeDetection); |
| 28 | + } |
| 29 | + |
| 30 | + override validate(): ValidationErrors | null { |
| 31 | + if (this.element.valid) { |
| 32 | + return null; |
| 33 | + } else if ( |
| 34 | + !this.element.valid && |
| 35 | + typeof this.element.min === 'number' && |
| 36 | + typeof this.element.valueAsNumber === 'number' && |
| 37 | + this.element.min > this.element.valueAsNumber |
| 38 | + ) { |
| 39 | + return { |
| 40 | + rangeUnderflow: { min: this.element.min, actual: this.element.valueAsNumber } |
| 41 | + }; |
| 42 | + } else if ( |
| 43 | + !this.element.valid && |
| 44 | + typeof this.element.max === 'number' && |
| 45 | + typeof this.element.valueAsNumber === 'number' && |
| 46 | + this.element.max < this.element.valueAsNumber |
| 47 | + ) { |
| 48 | + return { |
| 49 | + rangeOverflow: { max: this.element.max, actual: this.element.valueAsNumber } |
| 50 | + }; |
| 51 | + } else if (this.element.validity.valueMissing) { |
| 52 | + return { required: true }; |
| 53 | + } |
| 54 | + |
| 55 | + return null; |
| 56 | + } |
| 57 | +} |
0 commit comments