ngx-eagle
Version:
UI component infrastructure and Design components for mobile and desktop Angular web applications.
137 lines (121 loc) • 3.48 kB
text/typescript
import {
AfterViewChecked,
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
Output,
Renderer2,
ViewChild,
forwardRef,
} from '@angular/core';
import { Guid } from 'ngx-eagle/core/services';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NgxSize } from './typings';
export class CheckboxComponent
implements AfterViewChecked, AfterViewInit, ControlValueAccessor
{
checked: boolean = false;
indeterminate: boolean = false;
ngxColor: string | undefined | null = '#1890FF';
ngxSize: NgxSize | number = 'default';
inputCheckboxRef!: ElementRef;
disabled: boolean = false;
onChecked = new EventEmitter<boolean>();
onChange: any = () => {
this.onChecked.emit(this.checked);
};
onTouched: any = () => {};
public id: string = Guid.create();
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
this.disabled = elementRef.nativeElement.hasAttribute('disabled');
}
ngAfterViewChecked(): void {
this.setColor();
}
ngAfterViewInit(): void {
this.setColor();
if (typeof this.ngxSize === 'number') {
this.setSizeInNumber();
}
}
setSizeInNumber() {
const size = Number(this.ngxSize) / 16 + 'rem';
this.renderer.setStyle(this.inputCheckboxRef.nativeElement, 'width', size);
this.renderer.setStyle(this.inputCheckboxRef.nativeElement, 'height', size);
}
eventChecked(event: Event) {
const target = event.target as HTMLInputElement;
if (!this.disabled) {
this.checked = target.checked;
this.writeValue(this.checked);
}
}
setColor() {
if (!this.ngxColor) {
this.ngxColor = '#1890FF';
}
if (
this.inputCheckboxRef &&
(this.inputCheckboxRef.nativeElement.indeterminate ||
this.inputCheckboxRef.nativeElement.checked)
) {
this.renderer.setStyle(
this.inputCheckboxRef.nativeElement,
'background-color',
this.disabled ? '#9E9E9E' : this.ngxColor
);
} else {
this.renderer.setStyle(
this.inputCheckboxRef.nativeElement,
'background-color',
'transparent'
);
}
}
writeValue(checked: boolean): void {
this.checked = checked;
this.onChange(this.checked);
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(disabled: boolean): void {
this.disabled = disabled;
}
}