How to make Angular Forms ngModel classes inherit Bootstrap Forms classes

I use Bootstrap 4 to style my format controls and want to use form buffering styles when Angular ngModel adds CSS classes to forms like ng-valid, ng-invalid, ng-dirty, ng-pending .

For example, if I have the following view

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

and you want to apply the Bootstrap .has-danger class when the control has not passed data validation using Angular (i.e. when ngModel adds the .ng-invalid class). How can I accomplish this or something with an effect

  input.ng-invalid { /* inherit from bootstrap .form-control-danger */ } 
+5
source share
2 answers

I would use an ng class to apply bootstrap classes. Bootstrap defines the style of the classes after application.

 <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

+1
source

In Angular2, you can use the same approach as @Tyler's answer, but with a new syntax.

 <div class="form-group" [ngClass]="{ 'has-success': user.valid, 'has-error': user.invalid}" > <input type="text" class="form-control" id="usr" name="usr" required #user="ngModel" [(ngModel)]="model.usr" > </div> 

You create a new variable called user , line #user="ngModel" , which contains the state of the model for user input. And with [ngClass]="{ 'class-name': bool-expression}" you assign classes when expressions become true.

Keep in mind that you need to put class names as strings if they are not a valid JavaScript identifier (for example, they have - ).

0
source

All Articles