import { Component, OnChanges, forwardRef, ChangeDetectorRef } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { CustomInputComponent } from './../../_abstract/custom-input.component'; import { FriendlyValidationErrorsService } from './../../../services/friendly-validation-errors.service'; @Component({ selector: 'app-checkbutton', templateUrl: './checkbutton.component.html', styleUrls: ['./checkbutton.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CheckbuttonComponent), multi: true } ] }) export class CheckbuttonComponent extends CustomInputComponent implements OnChanges { exposeMetaInTemplate: string[] = ['label', 'value', 'disabled', 'checkedValue', 'onChange']; label: string; value?: string | boolean = true; isChecked: boolean; disabled = false; currentValue: string | number | boolean; checkedValue: string | number | boolean = true; onChange: (val) => void; readonly componentName = 'CheckbuttonComponent'; // For AOT compatibility, as class names don't survive minification constructor( protected valErrsService: FriendlyValidationErrorsService, protected _cdr: ChangeDetectorRef ) { super(valErrsService, _cdr); } ngOnChanges() { this.disabled = this._meta.disabled; } toggleChecked(e?: MouseEvent): void { if (e) { (e.target as HTMLElement).blur(); e.preventDefault(); } if (this.disabled) { return; } this.isChecked = !this.isChecked; this.currentValue = this.isChecked ? this.value || this.checkedValue : false; if (typeof this.onChange === 'function') { try { this.onChange(this.currentValue); } catch (e) { console.log('ERROR in onChange function'); } } this.propagateChange(this.currentValue); } writeValue(value: any): void { value = value ? this.checkedValue : false; this.isChecked = !!value; this.currentValue = this.isChecked ? this.checkedValue : false; this._cdr.markForCheck(); // We have to manually trigger change detection when using setValue or patchValue from outside this component } }