UNPKG

2.42 kBJavaScriptView Raw
1import { Directive, forwardRef, HostBinding, HostListener, Input } from '@angular/core';
2import { NG_VALUE_ACCESSOR } from '@angular/forms';
3// TODO: config: activeClass - Class to apply to the checked buttons
4export const CHECKBOX_CONTROL_VALUE_ACCESSOR = {
5 provide: NG_VALUE_ACCESSOR,
6 useExisting: forwardRef(() => ButtonCheckboxDirective),
7 multi: true
8};
9/**
10 * Add checkbox functionality to any element
11 */
12export class ButtonCheckboxDirective {
13 constructor() {
14 /** Truthy value, will be set to ngModel */
15 this.btnCheckboxTrue = true;
16 /** Falsy value, will be set to ngModel */
17 this.btnCheckboxFalse = false;
18 this.state = false;
19 this.isDisabled = false;
20 this.onChange = Function.prototype;
21 this.onTouched = Function.prototype;
22 }
23 // view -> model
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 // ControlValueAccessor
49 // model -> view
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}
64ButtonCheckboxDirective.decorators = [
65 { type: Directive, args: [{
66 selector: '[btnCheckbox]',
67 providers: [CHECKBOX_CONTROL_VALUE_ACCESSOR]
68 },] }
69];
70ButtonCheckboxDirective.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//# sourceMappingURL=button-checkbox.directive.js.map
\No newline at end of file