Skip to content

Instantly share code, notes, and snippets.

@lethiandev
Created September 29, 2021 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lethiandev/1036c1e4edb658f51b0c5dce31cfa18c to your computer and use it in GitHub Desktop.
Save lethiandev/1036c1e4edb658f51b0c5dce31cfa18c to your computer and use it in GitHub Desktop.
Most elegant Angular directive for forms validation feedback
import { Directive, DoCheck, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { ControlContainer } from '@angular/forms';
@Directive({
selector: '[appFormFeedback]',
})
export class FormFeedbackDirective implements DoCheck {
@Input('appFormFeedback') fieldName: string;
@Input('appFormFeedbackError') errorType: string;
constructor(
private parent: ControlContainer,
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef
) {}
ngDoCheck(): void {
const control = this.parent.control?.get(this.fieldName);
const feedbackVisible = control?.touched && !!control?.errors?.[this.errorType];
this.toggleTemplateView(feedbackVisible);
}
private toggleTemplateView(visible: boolean): void {
if (visible && this.viewContainerRef.length === 0) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else if (!visible && this.viewContainerRef.length > 0) {
this.viewContainerRef.clear();
}
}
}
<div class="form-group">
<label>Name<span class="text-red-500">*</span></label>
<input formControlName="name" type="text" class="form-control">
<div *appFormFeedback="'name'; error:'required'" class="form-control-feedback">
Name is required
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment