Skip to content

Commit

Permalink
feat: 🎸 add error class to input's parent
Browse files Browse the repository at this point in the history
  • Loading branch information
shaharkazaz committed Feb 10, 2021
1 parent 5951c9b commit 84949c3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
10 changes: 8 additions & 2 deletions projects/ngneat/error-tailor/src/lib/control-error.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export class ControlErrorsDirective implements OnInit, OnDestroy {
this.anchor = this.resolveAnchor();
this.control = (this.controlContainer || this.ngControl).control;
const hasAsyncValidator = !!this.control.asyncValidator;
const isInput = this.mergedConfig.blurPredicate(this.host.nativeElement);

const statusChanges$ = this.control.statusChanges.pipe(distinctUntilChanged());
const valueChanges$ = this.control.valueChanges;
Expand All @@ -76,7 +75,7 @@ export class ControlErrorsDirective implements OnInit, OnDestroy {
changesOnAsync$ = statusChanges$.pipe(startWith(true));
}

if (this.controlErrorsOnBlur && isInput) {
if (this.controlErrorsOnBlur && this.isInput) {
const blur$ = fromEvent(this.host.nativeElement, 'focusout');
// blurFirstThenUponChange
changesOnBlur$ = blur$.pipe(switchMap(() => valueChanges$.pipe(startWith(true))));
Expand Down Expand Up @@ -129,6 +128,10 @@ export class ControlErrorsDirective implements OnInit, OnDestroy {
this.clearRefs();
}

private get isInput() {
return this.mergedConfig.blurPredicate(this.host.nativeElement);
}

private clearRefs(): void {
if (this.customAnchorDestroyFn) {
this.customAnchorDestroyFn();
Expand All @@ -150,6 +153,9 @@ export class ControlErrorsDirective implements OnInit, OnDestroy {
}

const text = typeof getError === 'function' ? getError(controlErrors[firstKey]) : getError;
if (this.isInput) {
this.host.nativeElement.parentElement.classList.add('error-tailor-has-error');
}
this.setError(text, controlErrors);
} else if (this.ref) {
this.setError(null);
Expand Down
4 changes: 2 additions & 2 deletions src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ <h1>Custom Template</h1>

<h1>Show Errors On Submit (with Reset)</h1>

<form errorTailor>
<div class="form-group">
<form class="on-submit" errorTailor>
<div class="form-group on-submit">
<input
class="form-control"
ngModel
Expand Down
10 changes: 6 additions & 4 deletions src/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ body {
color: #dc3545;
}

.form-submitted input.ng-invalid,
.form-submitted select.ng-invalid {
border-color: #dc3545;
padding-right: calc(1.5em + 0.75rem);
.on-submit.form-submitted,
form:not(.on-submit) {
.ng-touched.ng-invalid {
border-color: #dc3545;
padding-right: calc(1.5em + 0.75rem);
}
}

0 comments on commit 84949c3

Please sign in to comment.