Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 2x 2x 2x 2x 2x 2x 1x 1x 1x | import { ChangeDetectionStrategy, Component, Input, OnChanges, OnDestroy, OnInit } from '@angular/core';
import { FormlyConfig, FormlyFieldConfig } from '@ngx-formly/core';
import { Observable, isObservable, of } from 'rxjs';
import { startWith, switchMap } from 'rxjs/operators';
import { FormsService } from 'ish-shared/forms/utils/forms.service';
/**
* Component that reads a fields validity status and displays active error messages.
*/
@Component({
selector: 'ish-validation-message',
template: '<small class="mt-1" id="{{ field.id }}-validation-error">{{ errorMessage$ | async | translate }} </small>',
changeDetection: ChangeDetectionStrategy.Default,
})
export class ValidationMessageComponent implements OnInit, OnChanges, OnDestroy {
@Input({ required: true }) field: FormlyFieldConfig;
@Input() id: string;
errorMessage$: Observable<string>;
constructor(private config: FormlyConfig) {}
ngOnInit(): void {
this.field.props = {
...this.field.props,
ariaDescribedByIds: FormsService.addAriaDescribedById(
this.field.props?.ariaDescribedByIds,
`${this.field.id}-validation-error`
),
};
}
ngOnDestroy(): void {
this.field.props.ariaDescribedByIds = FormsService.removeAriaDescribedById(
this.field.props.ariaDescribedByIds,
`${this.field.id}-validation-error`
);
}
ngOnChanges() {
this.errorMessage$ = this.field.formControl.statusChanges.pipe(
startWith(false),
switchMap(() => (isObservable(this.errorMessage) ? this.errorMessage : of(this.errorMessage)))
);
}
get errorMessage(): string | Observable<string> {
const fieldForm = this.field.formControl;
for (const error in fieldForm.errors) {
Iif (fieldForm.errors.hasOwnProperty(error)) {
// eslint-disable-next-line unicorn/no-null
Iif (fieldForm.errors[error] !== null && typeof fieldForm.errors[error] === 'object') {
Iif (fieldForm.errors[error].errorPath) {
return;
}
Iif (fieldForm.errors[error].message) {
return fieldForm.errors[error].message;
}
}
return this.determineErrorMessage(error);
}
}
}
private determineErrorMessage(error: string): string | Observable<string> {
let message = this.config.getValidatorMessage(error);
Iif (this.field.validation?.messages && this.field.validation.messages[error]) {
message = this.field.validation.messages[error];
}
Iif (this.field.validators?.[error]?.message) {
message = this.field.validators[error].message;
}
Iif (this.field.asyncValidators?.[error]?.message) {
message = this.field.asyncValidators[error].message;
}
Iif (typeof message === 'function') {
return message(this.field.formControl.errors[error], this.field);
}
return message;
}
}
|