Rey
Rey

Reputation: 13

How to apply different styles to same components in angular 13?

I have a reusable card component which contains heading , para and button. I want to use it 3 different pages, the content doesnt change but styling changes.

For eg: In page 1: card has padding of 10px, background-color: white and text-align: center

In page 2: card has padding of 16px and text-align: left and button background : lightblue

In page 2: card has text-align: center and button background : green

how to do it, should i add new style sheet or is there any other way to solve this problem

Upvotes: 1

Views: 58

Answers (2)

F1sher-Man
F1sher-Man

Reputation: 28

You can simply add string Input parameter to child component. Something like:

@Input() styleVariant: string;

then in your template file you would simply apply those:

<div id="container" class="{{styleVariant}}">
  //your code goes here
</div>

Different styleVariant classes you can keep in your child's style class with appropriate selectors, e.g.:

.some-option1 {
  card {
    padding: 10px;
    >button {
      background-color: white;
    }
  }
}

Simply pass the variant name of styles you want to apply.

<child-comp (styleVariant)="some-option1"></child-comp>

To make it cleaner and safer to use, you can define styleVariant not as a string but as an enum with available values.

Upvotes: 0

Ryan Baker
Ryan Baker

Reputation: 75

I think you would be able to use NgClass to solve your problem

https://angular.io/api/common/NgClass

Depending on how everything is written, you may also have to use a @Input and pass in some information to use in the NgClass statement

Upvotes: 0

Related Questions