@@ -2,7 +2,7 @@ import {Component, Input} from '@angular/core';
2
2
import { HttpClient , HttpEventType } from '@angular/common/http' ;
3
3
import { catchError , finalize } from 'rxjs/operators' ;
4
4
import { of } from 'rxjs' ;
5
- import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ;
5
+ import { AbstractControl , ControlValueAccessor , NG_VALIDATORS , NG_VALUE_ACCESSOR , ValidationErrors , Validator } from '@angular/forms' ;
6
6
7
7
8
8
@Component ( {
@@ -14,10 +14,15 @@ import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
14
14
provide : NG_VALUE_ACCESSOR ,
15
15
multi : true ,
16
16
useExisting : FileUploadComponent
17
+ } ,
18
+ {
19
+ provide : NG_VALIDATORS ,
20
+ multi : true ,
21
+ useExisting : FileUploadComponent
17
22
}
18
23
]
19
24
} )
20
- export class FileUploadComponent implements ControlValueAccessor {
25
+ export class FileUploadComponent implements ControlValueAccessor , Validator {
21
26
22
27
@Input ( )
23
28
requiredFileType :string ;
@@ -26,12 +31,16 @@ export class FileUploadComponent implements ControlValueAccessor {
26
31
27
32
fileUploadError = false ;
28
33
34
+ fileUploadSuccess = false ;
35
+
29
36
uploadProgress :number ;
30
37
31
38
onChange = ( fileName :string ) => { } ;
32
39
33
40
onTouched = ( ) => { } ;
34
41
42
+ onValidatorChange = ( ) => { } ;
43
+
35
44
disabled : boolean = false ;
36
45
37
46
constructor ( private http : HttpClient ) {
@@ -75,8 +84,9 @@ export class FileUploadComponent implements ControlValueAccessor {
75
84
this . uploadProgress = Math . round ( 100 * ( event . loaded / event . total ) ) ;
76
85
}
77
86
else if ( event . type == HttpEventType . Response ) {
87
+ this . fileUploadSuccess = true ;
78
88
this . onChange ( this . fileName ) ;
79
-
89
+ this . onValidatorChange ( ) ;
80
90
}
81
91
} ) ;
82
92
@@ -102,6 +112,29 @@ export class FileUploadComponent implements ControlValueAccessor {
102
112
this . disabled = disabled ;
103
113
}
104
114
115
+ registerOnValidatorChange ( onValidatorChange : ( ) => void ) {
116
+ this . onValidatorChange = onValidatorChange ;
117
+ }
118
+
119
+ validate ( control : AbstractControl ) : ValidationErrors | null {
120
+
121
+ if ( this . fileUploadSuccess ) {
122
+ return null ;
123
+ }
124
+
125
+ let errors : any = {
126
+ requiredFileType : this . requiredFileType
127
+ } ;
128
+
129
+ if ( this . fileUploadError ) {
130
+ errors . uploadFailed = true ;
131
+ }
132
+
133
+ return errors ;
134
+ }
135
+
136
+
137
+
105
138
106
139
}
107
140
0 commit comments