skip to Main Content

I’m trying to apply a class to a component using the host property of the component decorator, but it’s not working.

Here’s the HTML:

<div class="container">
 <app-header></app-header>
 <div class="content">
    <router-outlet/>
 </div>
</div>

Here’s the component

@Component({
  //...
  host: {
    'class': 'header-bg'
  },
  //...
 })
 export class HeaderComponent {}

And here’s the style:

.header-bg {
  background-color: aqua;
}

2

Answers


  1. It’s not clear where this style lives.
    I’m assuming it’s in the container component, since it’s not working.

    Angular encapsulates styles so they only apply to the component whose CSS file they live in.
    ::ng-deep is the naive approach, making global styles from a component-level CSS file.

    I would suggest adding the header-bg style in your app-header component instead. That should work.

    If you want to make the bg-color configurable, you could create an input on app-header like "headerColor" or "headerType" and add a class to the header based on that.

    Header TS:
    @Input() headerColor: string;

    Header HTML:
    <div class="header color-{{headerColor}}>

    Header CSS:
    .color-blue { background-color: blue }

    Container HTML:
    <app-header color="blue">

    Login or Signup to reply.
  2. The problem is probably due to the host element’s display property being inline by default and the template’s top level elements being block elements like div. If you have a block element inside an inline element then the block element is not going to show the inline element’s background. If there are no inline elements at the top level of the template then it will appear that the background is not working at all.

    You can change the host elements display type in a similar fashion to the way you added the class:

    @Component({
      // ..
      host: {
        class: 'header-bg',
        style: 'display: block' // or inline-block
      },
      // ...
    })
    export class HeaderComponent {}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search