UNPKG

3.17 kBJavaScriptView Raw
1import { Directive, HostBinding, HostListener, Input, forwardRef } from '@angular/core';
2import { NG_VALUE_ACCESSOR } from '@angular/forms';
3// TODO: config: activeClass - Class to apply to the checked buttons
4export var CHECKBOX_CONTROL_VALUE_ACCESSOR = {
5 provide: NG_VALUE_ACCESSOR,
6 useExisting: forwardRef(function () { return ButtonCheckboxDirective; }),
7 multi: true
8};
9/**
10 * Add checkbox functionality to any element
11 */
12export var ButtonCheckboxDirective = (function () {
13 function ButtonCheckboxDirective() {
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.onChange = Function.prototype;
20 this.onTouched = Function.prototype;
21 }
22 // view -> model
23 ButtonCheckboxDirective.prototype.onClick = function () {
24 if (this.isDisabled) {
25 return;
26 }
27 this.toggle(!this.state);
28 this.onChange(this.value);
29 };
30 ButtonCheckboxDirective.prototype.ngOnInit = function () {
31 this.toggle(this.trueValue === this.value);
32 };
33 Object.defineProperty(ButtonCheckboxDirective.prototype, "trueValue", {
34 get: function () {
35 return typeof this.btnCheckboxTrue !== 'undefined'
36 ? this.btnCheckboxTrue
37 : true;
38 },
39 enumerable: true,
40 configurable: true
41 });
42 Object.defineProperty(ButtonCheckboxDirective.prototype, "falseValue", {
43 get: function () {
44 return typeof this.btnCheckboxFalse !== 'undefined'
45 ? this.btnCheckboxFalse
46 : false;
47 },
48 enumerable: true,
49 configurable: true
50 });
51 ButtonCheckboxDirective.prototype.toggle = function (state) {
52 this.state = state;
53 this.value = this.state ? this.trueValue : this.falseValue;
54 };
55 // ControlValueAccessor
56 // model -> view
57 ButtonCheckboxDirective.prototype.writeValue = function (value) {
58 this.state = this.trueValue === value;
59 this.value = value ? this.trueValue : this.falseValue;
60 };
61 ButtonCheckboxDirective.prototype.setDisabledState = function (isDisabled) {
62 this.isDisabled = isDisabled;
63 };
64 ButtonCheckboxDirective.prototype.registerOnChange = function (fn) {
65 this.onChange = fn;
66 };
67 ButtonCheckboxDirective.prototype.registerOnTouched = function (fn) {
68 this.onTouched = fn;
69 };
70 ButtonCheckboxDirective.decorators = [
71 { type: Directive, args: [{ selector: '[btnCheckbox]', providers: [CHECKBOX_CONTROL_VALUE_ACCESSOR] },] },
72 ];
73 /** @nocollapse */
74 ButtonCheckboxDirective.ctorParameters = function () { return []; };
75 ButtonCheckboxDirective.propDecorators = {
76 'btnCheckboxTrue': [{ type: Input },],
77 'btnCheckboxFalse': [{ type: Input },],
78 'state': [{ type: HostBinding, args: ['class.active',] },],
79 'onClick': [{ type: HostListener, args: ['click',] },],
80 };
81 return ButtonCheckboxDirective;
82}());
83//# sourceMappingURL=button-checkbox.directive.js.map
\No newline at end of file