简体   繁体   中英

Angular best practice: for reusability, make new CSS class or new component?

I have this div and set of CSS properties (the properties themselves are unimportant, they're just examples) that are core to my app, and that I'll be reusing a lot throughout multiple pages and other components.

<div style="display: flex; flex-direction: column; height: 100%">
//here there will be some inner html that will vary based on the context it's being used in
</div>

Given that this is such simple html and that no data/event binding will interact with this div , what (and why) is the best pratice here:

  • new CSS class,
  • new angular component containing <ng-content></ng-content> inside,
  • something else?

Based in your example probably you will need a combination of both practices.

<div class="myBaseStyle">
    <ng-content></ng-content>
</div>

Where your css will look like this.

.myBaseStyle {
   display: flex;
   flex-direction: column;
   height: 100%
}

Since you want to reuse that div in several places, is a very good practice to create a component, since if you need to edit something in that particular DIV, you just to update it in one place and not in every location. What if in the future you need to add more html to that DIV, you will have to refacor your whole solution.

From what I could see, I gathered that the best solution is to simply make a CSS class, like so:

div.flex-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

Reasons:

  • KISS
  • doesn't introduce additional html nesting, which can cause friction with things like flexbox and therefore is less maintanable

In my view, angular components should only be created if either of the following criteria is met:

  • their template is consists of multiple html elements (in the example in the question there is only one)
  • they utilize custom logic, either in TypeScript or angular template syntax, eg ngIf

In your style.css under the src folder of the angular app, Make a global style like this:

<div class="flex-container">
  <ng-content></ng-content>
</div


.flex-container {
   display: flex;
   flex-direction: column;
   height: 100%;

   &.child-element { //like this you can add styles to chuld elements.
     ...
   }
}

In this way just copy and paste your HTML and styles will automatically be applied from style.css on the root.

If you want to edit the styles somewhere in the specific component then, in either case, you can @extend your styles from the style.css file into the x.compnent.css you will get the previous styles in x.compnent.css you can make further changes in your way.

Example to @extend styles:

@extend .flex-container;
  display: block;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM