4

If my main/parent component has the following:

<div class="main-wrapper">
  <app-inner></app-inner>
</div>

How might I add a class to the component being invoked inside?

The goal is that the app-inner component presents a class when rendered so that I might reference it in my CSS, such as:

<app-inner class="inner-comp">

However, neither this direct placement of the class attribute, nor [className], nor [ngClass] seem to actually add it.

CPHPython
  • 12,379
  • 5
  • 59
  • 71
  • 1
    You might want to use the tag selector for your use case. `app-inner { width: 100px }` – mamichels Mar 04 '20 at 17:26
  • Direct placement of `class` attribute should work on component tags. What style is not applying to your component? Can you share the properties of the CSS class `inner-comp`? – Shravan Mar 04 '20 at 17:33
  • @mamichels Thanks, but I am aware of that option. The project's lint rules do not allow that though (`selector-type-no-unknown`). – CPHPython Mar 04 '20 at 17:33
  • @Shravan placing the class attribute directly (``) does not work. When rendered the class attribute is simply not there. It's not a matter of how many properties/rules I have in my CSS. – CPHPython Mar 04 '20 at 17:36
  • Setting the class directly in the child component tag appears to work. Take a look at [this stackblitz](https://stackblitz.com/edit/angular-qeymjp?file=src%2Fapp%2Fapp.component.html). – ConnorsFan Mar 04 '20 at 17:39
  • @ConnorsFan thanks, I can see that in that example the _childClass_ is indeed rendered when it's placed in the parent's HTML... I wonder why the behavior is different in my case (several components do not render any class attribute). – CPHPython Mar 04 '20 at 17:44

1 Answers1

4

Without modifying the main/parent component's HTML, you might just simply use HostBinding in the InnerComponent:

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

export class InnerComponent implements OnInit {
  @HostBinding('className') componentClass: string;

  constructor() {
    this.componentClass = 'inner-comp';
  }
}

The declared string variable componentClass references directly the className's hostPropertyName ("DOM property that is bound to a data property").

This automatically adds to all invocations of <app-inner> the inner-comp class when the InnerComponent renders, which will then allow direct references in the parent component's CSS, such as:

.inner-comp { height: 100%; }
CPHPython
  • 12,379
  • 5
  • 59
  • 71