AngularJS | Conditional Class using ng-class

前端 未结 1 1285
抹茶落季
抹茶落季 2021-01-24 02:00

I\'m wanting to apply a conditional class to an element on the page.

Currently it\'s working with the following code:

ng-class=\"{ \'vfnz-form--error\'         


        
相关标签:
1条回答
  • 2021-01-24 02:24

    You could just do it in many ways, one simple way would be to use an object with bracket notation.

    Example:-

    ng-class="{ true: 'vfnz-form--error', false : 'vfnz-form--good'  }[loginForm.username.$invalid]"
    

    Or (since it cannot be both invalid and valid):-

    ng-class="{'vfnz-form--error' : loginForm.username.$invalid, 'vfnz-form--good' : loginForm.username.$valid}"
    

    And if you want to do it only if form is dirty you could yes add condition to check for $pristine/$dirty but you could also make use of the class angular adds on the inputs (and on the form as well) i.e ng-pristine/ng-dirty so you could define the rule with these class names to make it more specific.

    ex:-

    .vfnz-form--error .ng-dirty.something{/*apply bad rules*/} 
    
    0 讨论(0)
提交回复
热议问题