1 | import { Directive, forwardRef, HostBinding, HostListener, Input } from '@angular/core';
|
2 | import { NG_VALUE_ACCESSOR } from '@angular/forms';
|
3 |
|
4 | export const CHECKBOX_CONTROL_VALUE_ACCESSOR = {
|
5 | provide: NG_VALUE_ACCESSOR,
|
6 | useExisting: forwardRef(() => ButtonCheckboxDirective),
|
7 | multi: true
|
8 | };
|
9 |
|
10 |
|
11 |
|
12 | export class ButtonCheckboxDirective {
|
13 | constructor() {
|
14 |
|
15 | this.btnCheckboxTrue = true;
|
16 |
|
17 | this.btnCheckboxFalse = false;
|
18 | this.state = false;
|
19 | this.isDisabled = false;
|
20 | this.onChange = Function.prototype;
|
21 | this.onTouched = Function.prototype;
|
22 | }
|
23 |
|
24 | onClick() {
|
25 | if (this.isDisabled) {
|
26 | return;
|
27 | }
|
28 | this.toggle(!this.state);
|
29 | this.onChange(this.value);
|
30 | }
|
31 | ngOnInit() {
|
32 | this.toggle(this.trueValue === this.value);
|
33 | }
|
34 | get trueValue() {
|
35 | return typeof this.btnCheckboxTrue !== 'undefined'
|
36 | ? this.btnCheckboxTrue
|
37 | : true;
|
38 | }
|
39 | get falseValue() {
|
40 | return typeof this.btnCheckboxFalse !== 'undefined'
|
41 | ? this.btnCheckboxFalse
|
42 | : false;
|
43 | }
|
44 | toggle(state) {
|
45 | this.state = state;
|
46 | this.value = this.state ? this.trueValue : this.falseValue;
|
47 | }
|
48 |
|
49 |
|
50 | writeValue(value) {
|
51 | this.state = this.trueValue === value;
|
52 | this.value = value ? this.trueValue : this.falseValue;
|
53 | }
|
54 | setDisabledState(isDisabled) {
|
55 | this.isDisabled = isDisabled;
|
56 | }
|
57 | registerOnChange(fn) {
|
58 | this.onChange = fn;
|
59 | }
|
60 | registerOnTouched(fn) {
|
61 | this.onTouched = fn;
|
62 | }
|
63 | }
|
64 | ButtonCheckboxDirective.decorators = [
|
65 | { type: Directive, args: [{
|
66 | selector: '[btnCheckbox]',
|
67 | providers: [CHECKBOX_CONTROL_VALUE_ACCESSOR]
|
68 | },] }
|
69 | ];
|
70 | ButtonCheckboxDirective.propDecorators = {
|
71 | btnCheckboxTrue: [{ type: Input }],
|
72 | btnCheckboxFalse: [{ type: Input }],
|
73 | state: [{ type: HostBinding, args: ['class.active',] }, { type: HostBinding, args: ['attr.aria-pressed',] }],
|
74 | onClick: [{ type: HostListener, args: ['click',] }]
|
75 | };
|
76 |
|
\ | No newline at end of file |