1
1
import { FocusMonitor } from '@angular/cdk/a11y' ;
2
2
import { coerceBooleanProperty } from '@angular/cdk/coercion' ;
3
- import { Component , ElementRef , Input , OnDestroy } from '@angular/core' ;
4
- import { FormBuilder , FormGroup } from '@angular/forms' ;
3
+ import { Component , ElementRef , Input , OnDestroy , Optional , Self } from '@angular/core' ;
4
+ import { FormBuilder , FormGroup , ControlValueAccessor , NgControl } from '@angular/forms' ;
5
5
import { MatFormFieldControl } from '@angular/material' ;
6
6
import { Subject } from 'rxjs' ;
7
7
@@ -30,17 +30,18 @@ export class MyTel {
30
30
'[attr.aria-describedby]' : 'describedBy' ,
31
31
}
32
32
} )
33
- export class MyTelInput implements MatFormFieldControl < MyTel > , OnDestroy {
33
+ export class MyTelInput implements ControlValueAccessor , MatFormFieldControl < MyTel > , OnDestroy {
34
34
static nextId = 0 ;
35
35
36
36
parts : FormGroup ;
37
37
stateChanges = new Subject < void > ( ) ;
38
38
focused = false ;
39
- ngControl = null ;
40
39
errorState = false ;
41
40
controlType = 'example-tel-input' ;
42
41
id = `example-tel-input-${ MyTelInput . nextId ++ } ` ;
43
42
describedBy = '' ;
43
+ onChange = ( _ : any ) => { } ;
44
+ onTouched = ( ) => { } ;
44
45
45
46
get empty ( ) {
46
47
const { value : { area, exchange, subscriber} } = this . parts ;
@@ -89,17 +90,29 @@ export class MyTelInput implements MatFormFieldControl<MyTel>, OnDestroy {
89
90
this . stateChanges . next ( ) ;
90
91
}
91
92
92
- constructor ( fb : FormBuilder , private fm : FocusMonitor , private elRef : ElementRef < HTMLElement > ) {
93
+ constructor (
94
+ fb : FormBuilder ,
95
+ private fm : FocusMonitor ,
96
+ private elRef : ElementRef < HTMLElement > ,
97
+ @Optional ( ) @Self ( ) public ngControl : NgControl ) {
98
+
93
99
this . parts = fb . group ( {
94
100
area : '' ,
95
101
exchange : '' ,
96
102
subscriber : '' ,
97
103
} ) ;
98
104
99
105
fm . monitor ( elRef , true ) . subscribe ( origin => {
106
+ if ( this . focused && ! origin ) {
107
+ this . onTouched ( ) ;
108
+ }
100
109
this . focused = ! ! origin ;
101
110
this . stateChanges . next ( ) ;
102
111
} ) ;
112
+
113
+ if ( this . ngControl != null ) {
114
+ this . ngControl . valueAccessor = this ;
115
+ }
103
116
}
104
117
105
118
ngOnDestroy ( ) {
@@ -116,4 +129,24 @@ export class MyTelInput implements MatFormFieldControl<MyTel>, OnDestroy {
116
129
this . elRef . nativeElement . querySelector ( 'input' ) ! . focus ( ) ;
117
130
}
118
131
}
132
+
133
+ writeValue ( tel : MyTel | null ) : void {
134
+ this . value = tel ;
135
+ }
136
+
137
+ registerOnChange ( fn : any ) : void {
138
+ this . onChange = fn ;
139
+ }
140
+
141
+ registerOnTouched ( fn : any ) : void {
142
+ this . onTouched = fn ;
143
+ }
144
+
145
+ setDisabledState ( isDisabled : boolean ) : void {
146
+ this . disabled = isDisabled ;
147
+ }
148
+
149
+ _handleInput ( ) : void {
150
+ this . onChange ( this . parts . value ) ;
151
+ }
119
152
}
0 commit comments