checkbutton.component.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Component, OnChanges, forwardRef, ChangeDetectorRef } from '@angular/core';
  2. import { NG_VALUE_ACCESSOR } from '@angular/forms';
  3. import { CustomInputComponent } from './../../_abstract/custom-input.component';
  4. import { FriendlyValidationErrorsService } from './../../../services/friendly-validation-errors.service';
  5. @Component({
  6. selector: 'app-checkbutton',
  7. templateUrl: './checkbutton.component.html',
  8. styleUrls: ['./checkbutton.component.scss'],
  9. providers: [
  10. {
  11. provide: NG_VALUE_ACCESSOR,
  12. useExisting: forwardRef(() => CheckbuttonComponent),
  13. multi: true
  14. }
  15. ]
  16. })
  17. export class CheckbuttonComponent extends CustomInputComponent implements OnChanges {
  18. exposeMetaInTemplate: string[] = ['label', 'value', 'disabled', 'checkedValue', 'onChange'];
  19. label: string;
  20. value?: string | boolean = true;
  21. isChecked: boolean;
  22. disabled = false;
  23. currentValue: string | number | boolean;
  24. checkedValue: string | number | boolean = true;
  25. onChange: (val) => void;
  26. readonly componentName = 'CheckbuttonComponent'; // For AOT compatibility, as class names don't survive minification
  27. constructor(
  28. protected valErrsService: FriendlyValidationErrorsService,
  29. protected _cdr: ChangeDetectorRef
  30. ) {
  31. super(valErrsService, _cdr);
  32. }
  33. ngOnChanges() {
  34. this.disabled = this._meta.disabled;
  35. }
  36. toggleChecked(e?: MouseEvent): void {
  37. if (e) {
  38. (e.target as HTMLElement).blur();
  39. e.preventDefault();
  40. }
  41. if (this.disabled) { return; }
  42. this.isChecked = !this.isChecked;
  43. this.currentValue = this.isChecked ? this.value || this.checkedValue : false;
  44. if (typeof this.onChange === 'function') {
  45. try {
  46. this.onChange(this.currentValue);
  47. } catch (e) {
  48. console.log('ERROR in onChange function');
  49. }
  50. }
  51. this.propagateChange(this.currentValue);
  52. }
  53. writeValue(value: any): void {
  54. value = value ? this.checkedValue : false;
  55. this.isChecked = !!value;
  56. this.currentValue = this.isChecked ? this.checkedValue : false;
  57. this._cdr.markForCheck(); // We have to manually trigger change detection when using setValue or patchValue from outside this component
  58. }
  59. }