Skip to content

Commit

Permalink
feat(admin-ui): Allow custom error messages passed to FormFieldComponent
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbromley committed May 29, 2019
1 parent f7d337f commit 220d861
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { Directive, ElementRef, Optional } from '@angular/core';
import { FormControl, NgControl } from '@angular/forms';
import { NgControl } from '@angular/forms';

type InputElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;

// tslint:disable:directive-selector
@Directive({ selector: 'input, textarea, select' })
export class FormFieldControlDirective {
formControl: FormControl;
constructor(
private elementRef: ElementRef<InputElement>,
@Optional() private formControlName: NgControl,
@Optional() public formControlName: NgControl,
) {}

get valid(): boolean {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
<div class="form-group" [class.no-label]="!label">
<div
class="form-group"
[class.no-label]="!label"
[class.clr-error]="formFieldControl.formControlName.invalid"
>
<label *ngIf="label" [for]="for" class="clr-control-label">
{{ label }}
<clr-tooltip *ngIf="tooltip">
Expand Down Expand Up @@ -28,6 +32,7 @@
<clr-icon shape="edit"></clr-icon>
</button>
</div>
<div class="clr-subtext" *ngIf="getErrorMessage()">{{ getErrorMessage() }}</div>
<span class="tooltip-content">{{ label }} is required.</span>
</label>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ export class FormFieldComponent implements OnInit {
@Input() label: string;
@Input() for: string;
@Input() tooltip: string;
/**
* A map of error message codes (required, pattern etc.) to messages to display
* when those errors are present.
*/
@Input() errors: { [key: string]: string } = {};
/**
* If set to true, the input will be initially set to "readOnly", and an "edit" button
* will be displayed which allows the field to be edited.
Expand All @@ -42,4 +47,18 @@ export class FormFieldComponent implements OnInit {
this.formFieldControl.setReadOnly(value);
this.isReadOnly = value;
}

getErrorMessage(): string | undefined {
if (!this.formFieldControl || !this.formFieldControl.formControlName) {
return;
}
const errors = this.formFieldControl.formControlName.errors;
if (errors) {
for (const errorKey of Object.keys(errors)) {
if (this.errors[errorKey]) {
return this.errors[errorKey];
}
}
}
}
}

0 comments on commit 220d861

Please sign in to comment.