Proposal. Forms validations directive

In order to add validation error state we has-danger, form-control-danger and form-control-feedback css classes on different html elements

<div class="form-group has-danger">
   <label class="form-control-label" for="title">Title</label>
   <input type="text" class="form-control form-control-danger" formControlName="title" id="title">
   <div class="form-control-feedback">Title is required</div>

With angular it looks something like this

<div class="form-group" [ngClass]="{'has-danger': adForm.controls.title.invalid && adForm.controls.title.touched}">
   <label class="form-control-label" for="title">Title</label>
   <input type="text" class="form-control" [ngClass]="{'form-control-danger': adForm.controls.title.invalid && adForm.controls.title.touched}" formControlName="title" id="title">
   <div *ngIf="adForm.controls.title.invalid && adForm.controls.title.touched" class="form-control-feedback">Title is required</div>

I’m thinking about writing few directives to automatically handle all these css classes states so it can look as simple as this:

<div ngbFormGroup>
   <label for="title">Title</label>
   <input type="text" ngbFormControl formControlName="title" id="title">
   <div ngbFormControlFeedback>Title is required</div>

1 possible answer(s) on “Proposal. Forms validations directive

  1. Just for other people stumbling across this, I was in the same situation and had to update the approach of @jnizet for the new bootstrap version:

    import {ContentChild, Directive, HostBinding} from "@angular/core";
    import {NgControl} from "@angular/forms";
      selector: '.form-control:not([ngbNoFormControlValidation]),[ngbFormControlValidation]'
    export class NgbFormControlValidation {
      ngControl: NgControl;
      get isInvalid() {
        return this.ngControl && this.ngControl.dirty && this.ngControl.invalid;

    This does not take into account the “is-valid” state where green borders are added as I don’t need this right now.