opt-cc/static/src/app/common/show-error/show-error.component.ts

89 lines
2.9 KiB
TypeScript

import {Component, Input, OnInit} from '@angular/core';
import {FormGroup, NgForm} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';
import {SettingsService} from '../../services/settings.service';
@Component({
selector: 'show-error',
template: `
<div *ngIf="errorMessages" class="alert alert-danger">
<div *ngFor="let errorMessage of errorMessages">
{{errorMessage}}
</div>
</div>`
})
export class ShowErrorComponent {
// tslint:disable-next-line:no-input-rename
@Input('controlPath') controlPath;
// tslint:disable-next-line:no-input-rename
@Input('displayName') displayName = '';
private form: FormGroup;
constructor(ngForm: NgForm,
private translate: TranslateService,
private settingsService: SettingsService) {
this.form = ngForm.form;
this.settingsService.getLanguage().subscribe((language) => this.translate.setDefaultLang(language));
}
get errorMessages(): string[] {
const control = this.form.get(this.controlPath);
const messages = [];
if (!control || !(control.touched) || !control.errors) {
return null;
}
for (const code in control.errors) {
// Berechnung der lesbaren Fehlermeldungen
if (control.errors.hasOwnProperty(code)) {
const error = control.errors[code];
let message = '';
switch (code) {
case 'required':
this.translate.get('public.error.message.required', {fieldName: this.displayName})
.subscribe((res: string) => {
message = res;
});
break;
case 'minlength':
this.translate.get('public.error.message.min.length', {
fieldName: this.displayName,
boundary: error.requiredLength
})
.subscribe((res: string) => {
message = res;
});
break;
case 'maxlength':
this.translate.get('public.error.message.max.length', {
fieldName: this.displayName,
boundary: error.requiredLength
})
.subscribe((res: string) => {
message = res;
});
break;
case 'invalidEMail':
this.translate.get('public.error.message.email').subscribe((res: string) => {
message = res;
});
break;
case 'userNotFound':
this.translate.get('public.error.message.no.user').subscribe((res: string) => {
message = res;
});
break;
default:
this.translate.get('public.error.message.default', {fieldName: name}).subscribe((res: string) => {
message = res;
});
}
messages.push(message);
}
}
return messages;
}
}