-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
64 lines (53 loc) · 1.49 KB
/
index.ts
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
import { Directive, ElementRef } from '@angular/core'
import Cleave from 'cleave.js'
const availableTypes = [
'creditCard',
'phone',
'date',
'numeral'
]
@Directive({
selector: '[cleave]',
inputs: ['cleave']
})
export class CleaveDirective {
cleaveInstance = null
constructor(private el: ElementRef) {
this.el = el
}
set cleave(options: any){
let cleaveOpts = null
// simple type (see availableTypes)
if (typeof options === 'string' && availableTypes.indexOf(options) !== -1) {
cleaveOpts = {}
cleaveOpts[options] = true
}
// literal options object
if (typeof options === 'string' && options.match(/^\{/)) {
try {
cleaveOpts = JSON.parse(options)
} catch (e) {
console.error('Angular2 Cleave : options object could not be parsed. Check that JSON syntax is correct.')
}
}
// handle error if option is not available
if (typeof options === 'string' && cleaveOpts === null) {
console.error('Angular2 Cleave : option is not valid (%s).\n Available options : %s', options, availableTypes.join(', '))
}
// Cleave.js options object
if (typeof options === 'object') {
cleaveOpts = options
}
// let's go !
if (cleaveOpts !== null) {
this.initCleave(cleaveOpts)
}
}
// instanciate Cleave.js
private initCleave(opts) {
if (this.cleaveInstance) {
this.cleaveInstance.destroy();
}
this.cleaveInstance = new Cleave(this.el.nativeElement, opts)
}
}