Skip to content

Commit

Permalink
support formLevel errors
Browse files Browse the repository at this point in the history
  • Loading branch information
wouter-willems committed Jul 2, 2024
1 parent ebfa0f2 commit b91eab5
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 3 deletions.
15 changes: 15 additions & 0 deletions projects/demo/src/app/demo/demo.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,18 @@
<ng-template #myFancyTemplate>
This can be <span style="color: red;">ANYTHING</span>. <span style="color: green; font-weight: bold; font-size: 1.2rem;">Look at me me, i am BOLD AND GREEN</span>
</ng-template>

simple form with form level errors

<klp-form [formGroup]="simpleFormWithFormLevelErrors" [errors]="formErrors" errorMessageLocation="rightOfCaption">
<klp-form-element caption="First name" spaceDistribution="34-66" direction="vertical">
<klp-form-text-input formControlName="firstName" [clearable]="true">
</klp-form-text-input>
</klp-form-element>
<klp-form-element caption="Last name" spaceDistribution="34-66" direction="vertical">
<klp-form-text-input formControlName="lastName" [clearable]="true">
</klp-form-text-input>
</klp-form-element>

<klp-form-submit-button [submitCallback]="saveSimple">Save</klp-form-submit-button>
</klp-form>
23 changes: 21 additions & 2 deletions projects/demo/src/app/demo/demo.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {AppSelectOptions, SelectComponent} from '@klippa/ngx-enhancy-forms';
export class DemoComponent {
@ViewChild('myFancyTemplate') myFancyTemplate: TemplateRef<any>;
public formWarnings = new Map<AbstractControl, string | TemplateRef<any>>();
public formErrors = new Map<AbstractControl, string>();
constructor(private fb: FormBuilder) {

setTimeout(() => {
Expand Down Expand Up @@ -79,7 +80,7 @@ export class DemoComponent {
show = false;
isChecked: boolean = undefined;

private nameConfig = ['', [Validators.required, Validators.minLength(4)],
private nameConfig = ['', [],
[(e) => {
if (e.value?.length > 5) {
return Promise.resolve();
Expand All @@ -93,7 +94,7 @@ export class DemoComponent {
if (e.value?.length > 2) {
return Promise.resolve({async: 'daapaaa aaaaaaap aaaaap'});
}
return Promise.resolve({async: 'aapaaa '});
return Promise.resolve({});
}]
];

Expand Down Expand Up @@ -123,6 +124,11 @@ export class DemoComponent {
radioOption: null
});

public simpleFormWithFormLevelErrors = this.fb.group({
firstName: ['', [Validators.required]],
lastName: [''],
});

subForms = [];
options: AppSelectOptions = [
{id: 1, name: 'dra'},
Expand Down Expand Up @@ -234,6 +240,19 @@ export class DemoComponent {
await new Promise(resolve => setTimeout(resolve, 1000));
throw new Error('some error');
}
public saveSimple = async () => {
console.log('saving simple form');
console.log(this.simpleFormWithFormLevelErrors.get('firstName').errors);
this.formErrors.clear();
await new Promise((resolve, reject) => {
setTimeout(resolve, 1200);
});
if (new Date().getMilliseconds() > 500) {
this.formErrors.set(this.simpleFormWithFormLevelErrors.get('firstName'), 'Your first name is not cool enough');
}
this.formErrors.set(this.simpleFormWithFormLevelErrors.get('lastName'), 'Your last name makes no sense');
console.log(this.simpleFormWithFormLevelErrors.get('firstName').errors);
};

blurry() {
console.log('blurr');
Expand Down
2 changes: 1 addition & 1 deletion projects/klippa/ngx-enhancy-forms/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@klippa/ngx-enhancy-forms",
"version": "14.20.5",
"version": "14.21.0",
"publishConfig": {
"access": "public"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
<div *ngIf="showDefaultError('MatchPassword')">{{getErrorMessage("matchPassword")}}</div>
<div *ngIf="showDefaultError('date')">{{getErrorMessage("date")}}</div>
<div *ngIf="showDefaultError('message')">{{attachedControl.errors.message.value}}</div>
<div *ngIf="showDefaultError('formLevel')">{{getErrorMessage("formLevel")}}</div>
<div [ngTemplateOutlet]="getCustomErrorHandler(getErrorToShow())?.templateRef"></div>
</div>
</ng-template>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ export class FormElementComponent implements AfterViewInit {
}

getErrorMessage(key: keyof FormErrorMessages): string {
if (key === 'formLevel') {
return this.attachedControl.errors?.formLevel;
}
return this.customMessages?.[key]?.() ?? this.errorMessages[key];
}

Expand Down
27 changes: 27 additions & 0 deletions projects/klippa/ngx-enhancy-forms/src/lib/form/form.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export class FormComponent implements OnInit, OnDestroy, OnChanges {
@Input() public errorMessageLocation: 'belowCaption' | 'rightOfCaption' = 'belowCaption';
@Input() public formGroup: UntypedFormGroup;
@Input() public warnings: Map<AbstractControl, string | TemplateRef<any>> = new Map<AbstractControl, string | TemplateRef<any>>();
@Input() public errors: Map<AbstractControl, string> = new Map<AbstractControl, string>();
@Input() public patchValueInterceptor: (values: any) => Promise<any>;
@Output() public onInjected = new EventEmitter<Record<string, any>>();

Expand Down Expand Up @@ -93,6 +94,9 @@ export class FormComponent implements OnInit, OnDestroy, OnChanges {
if (isValueSet(simpleChanges.warnings?.currentValue)) {
this.patchFormWarningsMap();
}
if (isValueSet(simpleChanges.errors?.currentValue)) {
this.patchFormErrorsMap();
}
}

ngOnDestroy(): void {
Expand Down Expand Up @@ -130,6 +134,29 @@ export class FormComponent implements OnInit, OnDestroy, OnChanges {
};
}

private patchFormErrorsMap(): void {
const setFn = this.errors.set;
this.errors.set = (key: AbstractControl, value: string): Map<AbstractControl, string> => {
const prevVal = this.errors.get(key);
const result = setFn.call(this.errors, key, value);
key.setErrors({ ...key.errors, formLevel: value});
if (prevVal !== value) {
this.getFormElementByFormControl(key)?.determinePopupState();
}
return result;
};

const deleteFn = this.errors.delete;
this.errors.delete = (key: AbstractControl): boolean => {
const newErrorsObject = key.errors;
delete newErrorsObject.formLevel;
key.setErrors(newErrorsObject);
const result = deleteFn.call(this.errors, key);
this.getFormElementByFormControl(key)?.determinePopupState();
return result;
};
}

private addSupportForPatchValueInterceptor(): void {
const fn = this.formGroup.patchValue;
const newFn = (
Expand Down
1 change: 1 addition & 0 deletions projects/klippa/ngx-enhancy-forms/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface FormErrorMessages {
pattern: string;
matchPassword: string;
date: string;
formLevel?: string;
}

export type CustomErrorMessages = Record<keyof FormErrorMessages, () => string>;
Expand Down

0 comments on commit b91eab5

Please sign in to comment.