kenam
kenam

Reputation: 135

How can I reuse CSS styles between different components in Angular

Edit - Following comments and thinking this through a bit, I have added the options as I see them to the bottom of this question.

Original Question I have an Angular component (down below, html and scss file, nothing really in the component class for brevity). Lets call it "h5-underliner" and used like:

<app-h5-underliner>My Title</app-h5-underliner>

`

h5 {
    margin-bottom: 1.8rem;
    padding-bottom: 2rem;
    position: relative;
}

h5:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0.1rem;
    height: 0.2rem;
    width: 6rem;
    background: $colour-apg-accent;
}
<h5 [class]="colourThemeName">
    <ng-content></ng-content>
</h5>

`

Now say for example I want an "h2 underliner"

<app-h2-underliner>My Heading 2 Title</app-h2-underliner>

Which picks up the apps h2 styling.

How can I aceive this without duplicating all the css (which would end up something like the below:)

`

h2 {
    margin-bottom: 1.8rem;
    padding-bottom: 2rem;
    position: relative;
}

h2:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0.1rem;
    height: 0.2rem;
    width: 6rem;
    background: $colour-apg-accent;
}

`

It's not a huge example, but I dont like the repetition. I thought about a directive, but the pseudo selector after kills that idea (as far as I am aware).

Note there is a little bit of extra going on as the caller can choose a colour, but that just means more repetition between very similar components (i.e. only the h5 and h2 tags differ).


So options:

Option 1 - The mess abouve with <h2-underliner>Mt Title Text<\h2-underliner> and <h5-underliner>Mt Title Text<\h5-underliner> - bad for several reaons.

Option 2 - Global style for the css that can be applied to tags as required (.my-underliner) OR we make the decision that all h5 and h2 titles have this style. On one hand we set typography globally with mat custom typography - but it doesn't seem right to start adding global css for general css.

Option 3 - A component that follows the same pattern as material form field/content projection: <app-underliner><h5>My title text</h5></app-underliner> - in this case we contain the common style to one component and still have the freedom to use it with different headings.

Upvotes: 1

Views: 1465

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19193

Styles follow hierarchical override in angular. So if both of those components that you refer lets call them B, C are children of component A, then you can put those styles on component A.

Then B, C will inherit those styles from parent A

They don't even have to be direct children of A to inherit styles of A. So in a structure like

 A - D - C

 |_ B 

D, C , B will inherit styles declared in component A

Upvotes: 3

Related Questions