Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Angular Forms ngModel classes inherit from Bootstrap Forms classes

I am using Bootstrap 4 to style my form controls, and want to use the Bootstrap Forms validation styles when Angular's ngModel adds CSS classes to forms, such as ng-valid, ng-invalid, ng-dirty, ng-pending.

For example, if I have the following form

 <form novalidate>
     <input type="email" class="form-control" ng-model="user.email" required />
 </form>

and want to apply Bootstrap's .has-danger class when the control fails data validation with Angular (i.e. when ngModel adds the class .ng-invalid). How do I accomplish this or something to the effect of

  input.ng-invalid {
    /* inherit from bootstrap's 
    .form-control-danger   */
  }  
like image 521
T. Webster Avatar asked Nov 09 '22 15:11

T. Webster


1 Answers

I would use ng-class for applying the bootstrap classes. Bootstrap defines the styling of the classes once applied.

<form name='myForm'>
    <input type="email" name='input' class="form-control" ng-model="user.email" ng-class="myForm.input.$valid ? '' : 'has-danger' " required />
//or get fancy with the object argument form of ng-class
... ng-minlength='3' ng-class="{
      has-success: myForm.input.$valid,
      has-warning: myForm.input.$error.minlength,
      has-error: myForm.input.$error.required}"

Checkout: https://docs.angularjs.org/api/ng/directive/form

like image 78
Tyler Avatar answered Nov 15 '22 07:11

Tyler