Currently, I am engaged in a project using AngularJS with the intention of gradually organizing things for Angular 6 or whichever version is available when we begin the upgrade process. A significant part of this endeavor involves converting existing directives into components.
The main issue I am facing is that each instance of a component adds an extra element to the DOM, wrapping my actual component HTML and disrupting the hierarchy. This makes it quite challenging to write CSS that functions as intended.
To better illustrate my predicament, consider a basic component named alert
designed to style various types of messages meant to grab a user's attention. It has two bindings - message
and type
. Depending on the type
, special styling will be applied along with possibly displaying a unique icon. All display logic should be contained within the component so that users simply need to ensure they input the data correctly for it to function properly.
<alert message="someCtrl.someVal" type="someCtrl.someVal"></alert>
Option A: add styling to a <div>
inside the additional element
Component template
<div
class="alert"
ng-class="{'alert--success': alert.type === 'success', 'alert--error': alert.type === 'error'}">
<div class="alert__message">{{alert.message}}</div>
<a class="alert__close" ng-click="alert.close()">
</div>
Sass
.alert {
& + & {
margin-top: 1rem; // will not work as intended
}
&--success {
background-color: green; // functional
}
&--error {
background-color: red; // functional
}
}
This method works well if the component remains unaware of its surroundings. However, once you want to place it inside a flex-parent or utilize a selector like "+", issues arise.
Option B: attempt to style the additional element directly
Component template
<div class="alert__message">{{alert.message}}</div>
<a class="alert__close" ng-click="alert.close()">
Sass
alert {
& + & {
margin-top: 1rem; // now functional
}
.alert--success {
background-color: green; // no designated location for placement
}
.alert--error {
background-color: red; // no designated location for placement
}
}
Now, the issue shifts to finding where to apply modifier classes for success and error conditions.
Is there something I am overlooking? What would be the optimal approach to address the presence of this additional element that exceeds the confines of the component itself?