Should I write CSS using ng-if as CSS Attribute Selector?
Given the best practices in Angular, I'm wondering if I should use CSSng-if
as an attribute selector or not.
Below is the HTML and CSS code for your reference.
Html
<span ng-class="{'has__hardcoded-value' : user.isManualEdit}">
{{user.totalScore}}
<span ng-if="user.isManualEdit" class="alert-default">*</span>
</span>
CSS
span.has__hardcoded-value {
position: relative;
}
span.has__hardcoded-value > [ng-if="user.isManualEdit"] {
position: absolute;
right: -7px;
top: -7px;
}
Any input would be appreciated.
Thank you in advance:)
source to share
No, don't do this.
Angular's use of certain attributes in CSS ties your design / layout to Angular. You cannot change your JavaScript framework without changing your CSS. You can't even upgrade to Angular 2+ without changing the CSS as the attribute ng-if
no longer exists. Also, you will have to update your CSS anytime the logic changes. This connection is bad and should be avoided.
Use selectors for elements, classes, and identifiers instead.
source to share
There are a number of reasons. I'll go with a pretty practical option.
You have three things:
- CSS style
- HTML structure
- JS code
you want them to be as separate as possible so that you can modify one without much danger of messing up the other.
When you do this:
span.has__hardcoded-value > [ng-if="user.isManualEdit"] {
you basically make your style definition dependent on both structure and code. Now if you want, for example, to change ng-if to ng-show / hide, or if you want to refactor your code to use different variable names, your style definition should change as well.
Now it all depends on your code. If you are just making a prototype of a drop that you will drop in the evening - who cares about how you do it. If you have been doing something for a longer time, it must be saved and then followed by best practices in terms of https://en.wikipedia.org/wiki/Separation_of_concerns
source to share