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

by habit   Last Updated September 16, 2019 02:26 AM

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?
Tags : html css angular


Answers 2


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.

Diego Bascans
Diego Bascans
September 15, 2019 23:45 PM

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:

  • K.I.S.S.
  • 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, e.g. ngIf
habit
habit
September 16, 2019 02:17 AM

Related Questions


Binding ngModel to complex data

Updated May 20, 2017 04:26 AM


Angular disabling button and mat-input error message

Updated December 17, 2018 14:26 PM