-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathngxerrors.directive.ts
More file actions
executable file
·89 lines (69 loc) · 2.12 KB
/
ngxerrors.directive.ts
File metadata and controls
executable file
·89 lines (69 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Directive, Input, OnChanges, OnDestroy, AfterViewInit } from '@angular/core';
import { FormGroupDirective, AbstractControl } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { ErrorDetails, ErrorOptions } from './ngxerrors';
import { toArray } from './utils/toArray';
@Directive({
selector: '[ngxErrors]',
exportAs: 'ngxErrors'
})
export class NgxErrorsDirective implements OnChanges, OnDestroy, AfterViewInit {
@Input('ngxErrors')
controlName: string;
subject = new BehaviorSubject<ErrorDetails>(null);
control: AbstractControl;
ready: boolean = false;
constructor(
private form: FormGroupDirective
) { }
get errors() {
if (!this.ready) return;
return this.control.errors;
}
get hasErrors() {
return !!this.errors;
}
hasError(name: string, conditions: ErrorOptions): boolean {
return this.checkPropState('invalid', name, conditions);
}
isValid(name: string, conditions: ErrorOptions): boolean {
return this.checkPropState('valid', name, conditions);
}
getError(name: string) {
if (!this.ready) return;
return this.control.getError(name);
}
private checkPropState(prop: string, name: string, conditions: ErrorOptions): boolean {
if (!this.ready) return;
const controlPropsState = (
!conditions || toArray(conditions).every((condition: string) => this.control[condition])
);
if (name.charAt(0) === '*') {
return this.control[prop] && controlPropsState;
}
return (
prop === 'valid' ? !this.control.hasError(name) : this.control.hasError(name) && controlPropsState
);
}
private checkStatus() {
const control = this.control;
const errors = control.errors;
this.ready = true;
if (!errors) return;
for (const errorName in errors) {
this.subject.next({ control, errorName });
}
}
ngOnChanges() {
this.control = this.form.control.get(this.controlName);
}
ngAfterViewInit() {
setTimeout(() => {
this.checkStatus();
this.control.statusChanges.subscribe(this.checkStatus.bind(this));
});
}
ngOnDestroy() {
this.subject.unsubscribe();
}
}