Created
September 29, 2021 19:28
-
-
Save lethiandev/1036c1e4edb658f51b0c5dce31cfa18c to your computer and use it in GitHub Desktop.
Most elegant Angular directive for forms validation feedback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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