diff --git a/src/lib/form/base-form.component.ts b/src/lib/form/base-form.component.ts index 4ae779e..c93d71a 100644 --- a/src/lib/form/base-form.component.ts +++ b/src/lib/form/base-form.component.ts @@ -1,14 +1,24 @@ import { Directive } from '@angular/core'; import { FormGroup } from '@angular/forms'; -import { hasFormChanged } from '@iqser/common-ui'; +import { AutoUnsubscribe, hasFormChanged } from '@iqser/common-ui'; @Directive() -export class BaseFormComponent { +export abstract class BaseFormComponent extends AutoUnsubscribe { form!: FormGroup; initialFormValue; - get changed() { + constructor() { + super(); + } + + get changed(): boolean { return hasFormChanged(this.form, this.initialFormValue); } + + get valid(): boolean { + return this.form?.valid; + } + + abstract save(): Promise; } diff --git a/src/lib/utils/functions.ts b/src/lib/utils/functions.ts index 133feb4..b9e38ec 100644 --- a/src/lib/utils/functions.ts +++ b/src/lib/utils/functions.ts @@ -38,30 +38,32 @@ export function trackBy() { export function hasFormChanged(form: FormGroup, initialFormValue): boolean { - for (const key of Object.keys(form.getRawValue())) { - const initialValue = initialFormValue[key]; - const updatedValue = form.get(key).value; + if (form && initialFormValue) { + for (const key of Object.keys(form.getRawValue())) { + const initialValue = initialFormValue[key]; + const updatedValue = form.get(key).value; - if (initialValue == null && updatedValue != null) { - const updatedValueType = typeof updatedValue; - if (updatedValueType !== 'string' && updatedValueType !== 'boolean') { - return true; - } else if (updatedValueType === 'string' && updatedValue.length > 0) { - return true; - } else if (updatedValueType === 'boolean' && updatedValue === true) { - return true; - } - } else if (initialValue !== updatedValue) { - if (Array.isArray(updatedValue)) { - if (JSON.stringify(initialValue) !== JSON.stringify(updatedValue)) { + if (initialValue == null && updatedValue != null) { + const updatedValueType = typeof updatedValue; + if (updatedValueType !== 'string' && updatedValueType !== 'boolean') { + return true; + } else if (updatedValueType === 'string' && updatedValue.length > 0) { + return true; + } else if (updatedValueType === 'boolean' && updatedValue === true) { return true; } - } else if (updatedValue instanceof moment) { - if (!moment(updatedValue).isSame(moment(initialValue))) { + } else if (initialValue !== updatedValue) { + if (Array.isArray(updatedValue)) { + if (JSON.stringify(initialValue) !== JSON.stringify(updatedValue)) { + return true; + } + } else if (updatedValue instanceof moment) { + if (!moment(updatedValue).isSame(moment(initialValue))) { + return true; + } + } else { return true; } - } else { - return true; } } }