skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search