Same styling across multiple components in Angular

65 views Asked by At

I have multiple(around 6) components (HTML) having the same styling like

<headertag>Some Content</headertag> <headertag>Some subtitle</headertag> Here there might be different content or svg/img or input fields. <button>accept</button> <button>cancel</button>

How Can I add a common style for this situation.

For ex: Each stylesheet will have. h2 { margin-top: 0; margin-bottom: 30px; color: Blue; } button { display: flex; flex-direction: column; }

How do I remove the repetitive styles from each stylesheet. We are using scss. Any tips please Thanks

I was thinking about mixins but felt it is not a good option.

3

There are 3 answers

4
Marty On

You can use the "Base Stylesheet" -> If the styles are very common across multiple components, you can create a base stylesheet that contains these common styles. Then, import this base stylesheet into your component stylesheets.

// this is in file: _base.scss
h2 {
  margin-top: 0;
  margin-bottom: 30px;
  color: blue;
}
button {
  display: flex;
  flex-direction: column;
}

And in your component where you want to use the base style SCSS:

@import 'base';

Hope this is the one you was looking for. Have a nice day

0
Naren Murali On

You can use the host property of @Component selector and add a common class for all the components, then in the global styles you can add.

global_styles.css

.common-changes h2 {
  margin-top: 0;
  margin-bottom: 30px;
  color: Blue;
}
.common-changes button {
  margin-top: 0;
  margin-bottom: 30px;
  color: Blue;
}

child component - one of multiple

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  template: `
  <h2 >Some Content</h2 > 
  <h2 >Some subtitle</h2 > 
  Here there might be different content or svg/img or input fields. 
  <button>accept</button> 
  <button>cancel</button>
  `,
  host: {
    class: 'common-changes',
  },
  standalone: true,
})
export class AComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

stackblitz

0
Sam Scholefield On

Another approach not already mentioned here is that Angular components are able to accept an array of stylesheets:

@Component({
    selector: 'info-dialog',
    standalone: true,
    imports: [CommonModule],
    templateUrl: './info-dialog.component.html',
    styleUrls: ['./info-dialog.component.scss', '../styles/dialogs.scss'],
})

In the simple example above, styles unique to the info-dialog component can be maintained independently of a common shared stylesheet for all dialogs.