improve base form component typings

This commit is contained in:
Dan Percic 2022-09-23 14:48:37 +03:00
parent 440b8e6b82
commit f658315254
2 changed files with 26 additions and 23 deletions

View File

@ -5,7 +5,7 @@ import { hasFormChanged } from '../utils';
@Directive()
export abstract class BaseFormComponent {
form!: UntypedFormGroup;
initialFormValue!: Record<string, string>;
initialFormValue!: Record<string, string | number | boolean>;
get changed(): boolean {
return hasFormChanged(this.form, this.initialFormValue);

View File

@ -41,36 +41,39 @@ export function trackByFactory<T extends ITrackable<PrimaryKey>, PrimaryKey exte
return (_index: number, item: T): Id => item.id;
}
export function hasFormChanged(form: UntypedFormGroup, initialFormValue: Record<string, string>): boolean {
if (form && initialFormValue) {
for (const key of Object.keys(form.getRawValue())) {
const initialValue = initialFormValue[key];
const updatedValue = form.get(key)?.value;
export function hasFormChanged(form: UntypedFormGroup, initialFormValue: Record<string, string | number | boolean>): boolean {
if (!form || !initialFormValue) {
return false;
}
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) {
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)) {
return true;
}
} else if (initialValue !== updatedValue) {
if (Array.isArray(updatedValue)) {
if (JSON.stringify(initialValue) !== JSON.stringify(updatedValue)) {
return true;
}
} else if (updatedValue instanceof dayjs) {
if (!(updatedValue as Dayjs).isSame(dayjs(initialValue), 'day')) {
return true;
}
} else {
} else if (updatedValue instanceof dayjs && typeof initialValue === 'string') {
if (!(updatedValue as Dayjs).isSame(dayjs(initialValue), 'day')) {
return true;
}
} else {
return true;
}
}
}
return false;
}