0

I normally use a global SCSS file in my apps, but today I wanted to make some scss scoped to just my component.

I have set a class on the component via @HostBinding (of class.card).

I can style items inside my component, such as the caard-body, but how can I apply overrides to this component's card class?

In other words, I have several cards on the page. I have styles that I only want to apply to this card, to make it look different. So I'd like to apply css such as

.card { background-color: violet; }

So that only this card is violet. I want to make this css part of this component, so everywhere I use it it will automatically be a violet card. (In reality I want to more than a simple thing, but you get the idea)

My component TS:

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

@Component({
  selector: 'app-reviews',
  templateUrl: './reviews.component.html',
  styleUrls: ['./reviews.component.scss']
})
export class ReviewsComponent {
  @HostBinding('class.card')
  true;

  @Input()
  review;

  constructor() {}
}

My Component SCSS:

.card-header {
  border: 0;
  color: #cf0989;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  font-size: 2rem;
  font-weight: normal;
}

.card-body {
   ...
}

My component HTML:

<div class="card-header">Testimonials</div>
<div class="card-body">

  <div class="review-image">
    <img class="rounded-circle"
        alt="{{review.acf.article_author.post_title}}"
        src="{{review.acf.article_author.acf.image}}">
  </div>

  <div class="review-content">
    <p class="review">
      <span [innerHTML]="review.content.rendered"></span>
    </p>
    <p class="reviewer-name">{{review.acf.article_author.post_title}}</p>
  </div>

</div>

The selectors in my CSS for .card-body and .card-header work fine, but I cannot style this .card. Adding this, for example does nothing:

.card { background-color: violet: }

How can I create SCSS selectors in the component's SCSS file that also apply to the class applied to the component via @HostBinding? Can I? Should I?

Steve
  • 14,401
  • 35
  • 125
  • 230

1 Answers1

0

It looks like I need to use :host, is that correct?

:host {
  &.card {
    padding: 2rem;
  }
}
Steve
  • 14,401
  • 35
  • 125
  • 230
  • 1
    You can do that but as it's generally speaking not always best practice and should be avoided if possible. If the styles you want to apply is part of the concern of this component itself, I would suggest you add a wrapper tag for your template. `
    your card header and body tags
    `. Then you can style it normally without any tricks or workarounds.
    – Xinan Oct 17 '18 at 16:22