Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, ElementRef, Input, Output, EventEmitter, ViewEncapsulation, forwardRef, ViewChild, Injector } from '@angular/core';
- import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgModel, NgControl, ValidationErrors } from '@angular/forms';
- import { MomentDateAdapter } from '@angular/material-moment-adapter';
- import { MAT_DATE_LOCALE, DateAdapter, MAT_DATE_FORMATS, MatDatepicker } from '@angular/material';
- import { ObjectHelper } from '../helper/object-helper';
- import { TranslateService } from '@ngx-translate/core';
- import * as moment from 'moment';
- export const YEARMONTHINPUT_CONTROL_VALUE_ACCESSOR: any = {
- provide: NG_VALUE_ACCESSOR,
- useExisting: forwardRef(() => YearMonthInputComponent),
- multi: true
- };
- export const MY_FORMATS = {
- parse: {
- dateInput: 'MM/YYYY',
- },
- display: {
- dateInput: 'MM/YYYY',
- monthYearLabel: 'MMM YYYY',
- dateA11yLabel: 'LL',
- monthYearA11yLabel: 'MMMM YYYY',
- },
- };
- @Component({
- selector: 'app-year-month',
- templateUrl: 'year-month-input.component.html',
- encapsulation: ViewEncapsulation.None,
- providers: [
- YEARMONTHINPUT_CONTROL_VALUE_ACCESSOR,
- { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
- { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
- ]
- })
- export class YearMonthInputComponent implements ControlValueAccessor {
- public static nextId = 0;
- @Output() public valueChange: EventEmitter<any>;
- @ViewChild('yearMonthInput') public yearMonthInput: ElementRef;
- @ViewChild('input') public input: NgModel;
- public mask: any[];
- public value: Date;
- public selectedValue: Date;
- public errorState: boolean;
- public errorMessage: string;
- public styleClass: any;
- private _name: string;
- private _errorKey: string;
- private _placeholder: string;
- private _required: boolean;
- private _disabled: boolean;
- private _focus: boolean;
- private _message: string;
- private _floatLabel: boolean;
- private yearMonthRegex = new RegExp(/^(0?[1-9]|1[012])[\/\-]\d{4}$/);
- private yearMonthRegexWithoutSpecialCharacter = new RegExp(/^(0?[1-9]|1[012])\d{4}$/);
- public propagateChange = (_: any) => { /* do nothing */ };
- public propagateTouch = (_: any) => { /* do nothing */ };
- constructor(
- private injector: Injector,
- private translateService: TranslateService
- ) {
- this.valueChange = new EventEmitter<any>();
- this.name = `app-year-month-${YearMonthInputComponent.nextId++}`;
- this.placeholder = null;
- this.required = false;
- this.floatLabel = true;
- this.errorState = false;
- this.errorMessage = null;
- this.disabled = false;
- this.mask = [];
- this.styleClass = { width: 'auto' };
- }
- public writeValue(value: any): void {
- if (value === null || value === undefined || value === '') {
- this.value = null;
- this.selectedValue = null;
- } else {
- const strValue = (value + '').trim();
- if (!isNaN(Number(value)) && strValue.length === 6) {
- const dateValue = moment(strValue.substr(0, 4) + '-' + strValue.substr(4, 6) + '-01').toDate();
- this.value = dateValue;
- this.selectedValue = dateValue;
- } else {
- this.value = null;
- this.selectedValue = null;
- }
- }
- }
- public registerOnChange(fn: (_: any) => {}): void {
- this.propagateChange = fn;
- }
- public registerOnTouched(fn: (_: any) => {}): void {
- this.propagateTouch = fn;
- }
- public setDisabledState(isDisabled: boolean): void {
- this.disabled = isDisabled;
- }
- @Input()
- public get name(): string { return this._name; }
- public set name(name: string) { this._name = name; }
- @Input()
- public get errorKey(): string { return this._errorKey; }
- public set errorKey(errorKey: string) { this._errorKey = errorKey; }
- @Input()
- public get placeholder(): string { return this._placeholder; }
- public set placeholder(placeholder: string) { this._placeholder = placeholder; }
- @Input()
- public get required(): boolean { return this._required; }
- public set required(required: boolean) { this._required = required; }
- @Input()
- public get focus(): boolean { return this._focus; }
- public set focus(focus: boolean) {
- this._focus = focus;
- if (focus === true) {
- this.yearMonthInput.nativeElement.focus();
- }
- }
- @Input()
- public get message(): string { return this._message; }
- public set message(message: string) { this._message = message; }
- @Input()
- public get floatLabel(): boolean { return this._floatLabel; }
- public set floatLabel(floatLabel: boolean) { this._floatLabel = floatLabel; }
- @Input()
- public get disabled(): boolean { return this._disabled; }
- public set disabled(disabled: boolean) { this._disabled = disabled; }
- public _onValueChange(value) {
- if (value) {
- if (value instanceof Date) {
- if (moment(value).isValid()) {
- this.value = moment(value).toDate();
- this.propagateChange(moment(value).format('YYYYMM'));
- this.valueChange.emit(moment(value).format('YYYYMM'));
- } else {
- this.value = null;
- this.propagateChange(null);
- this.valueChange.emit(null);
- }
- } else {
- // format : MM/YYYY
- const strYearMonth = String(value.creationData().input);
- if (strYearMonth.length === 7) {
- if (this.yearMonthRegex.test(strYearMonth)) {
- this.errorState = false;
- const formatedValue = strYearMonth.substr(3, 4) + '' + strYearMonth.substr(0, 2);
- // Note : new Date month start from 0 to 11
- this.value = new Date(Number(strYearMonth.substr(3, 4)), Number(strYearMonth.substr(0, 2)) - 1, 1);
- this.propagateChange(formatedValue);
- this.valueChange.emit(formatedValue);
- } else {
- this.errorState = true;
- this.value = null;
- this.propagateChange(null);
- this.valueChange.emit(null);
- }
- } else if (strYearMonth.length === 6) {
- if (this.yearMonthRegexWithoutSpecialCharacter.test(String(value.creationData().input))) {
- this.errorState = false;
- const formatedValue = strYearMonth.substr(2, 4) + '' + strYearMonth.substr(0, 2);
- // Note : new Date month start from 0 to 11
- this.value = new Date(Number(strYearMonth.substr(3, 4)), Number(strYearMonth.substr(0, 2)) - 1, 1);
- this.propagateChange(formatedValue);
- this.valueChange.emit(formatedValue);
- } else {
- this.errorState = true;
- this.value = null;
- this.propagateChange(null);
- this.valueChange.emit(null);
- }
- } else {
- this.errorState = true;
- this.value = null;
- this.propagateChange(null);
- this.valueChange.emit(null);
- }
- }
- this.validate();
- } else {
- this.propagateChange(value);
- this.valueChange.emit(value);
- this.validate();
- }
- }
- public chosenYearHandler(normalizedYear: moment.Moment) {
- this.value = moment(normalizedYear).toDate();
- const ctrlValue = moment(this.value);
- ctrlValue.year(normalizedYear.year());
- this.value = moment(ctrlValue).toDate();
- }
- public chosenMonthHandler(normlizedMonth: moment.Moment, datepicker: MatDatepicker<moment.Moment>) {
- this.value = moment(normlizedMonth).toDate();
- this.selectedValue = moment(normlizedMonth).toDate();
- const ctrlValue = moment(this.value);
- ctrlValue.month(normlizedMonth.month());
- this.propagateChange(moment(ctrlValue).format('YYYYMM'));
- this.valueChange.emit(moment(ctrlValue).format('YYYYMM'));
- this.value = moment(ctrlValue).toDate();
- this.selectedValue = moment(ctrlValue).toDate();
- this.input.control.setValue(moment(ctrlValue).toDate());
- datepicker.close();
- this.validate();
- }
- private validate() {
- this.styleClass = { width: this.yearMonthInput.nativeElement.clientWidth ? 'calc(' + this.yearMonthInput.nativeElement.clientWidth + 'px)' : 'auto' };
- try {
- const ngControl: NgControl | NgModel = this.injector.get(NgControl);
- let errors: ValidationErrors = {};
- if (ngControl instanceof NgModel) {
- if (this.input.valid) {
- this.errorState = false;
- } else {
- this.errorState = true;
- }
- errors = this.input.errors;
- } else {
- if (ngControl.invalid) {
- this.errorState = true;
- } else {
- this.errorState = false;
- }
- errors = ngControl.errors;
- }
- for (const key in errors) {
- if (key) {
- let keyMessage = null;
- let params = null;
- if (errors.matDatepickerParse) {
- keyMessage = ObjectHelper.composeMessageKey(this.message, this.errorKey, 'pattern');
- params = null;
- } else {
- keyMessage = ObjectHelper.composeMessageKey(this.message, this.errorKey, key);
- params = ObjectHelper.composeMessageParams(this.message, key, errors);
- }
- if (params) {
- this.translateService.get(keyMessage, params).subscribe(
- (result) => {
- this.errorMessage = result;
- }
- );
- } else {
- this.translateService.get(keyMessage).subscribe(
- (result) => {
- this.errorMessage = result;
- }
- );
- }
- break;
- }
- }
- } catch (exception) {
- console.warn('[YearMonthInput] Forms / NgModel not defined!', exception);
- }
- }
- public markInputAsTouched() {
- this.validate();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment