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.

6
  • 1
    You might want to use the tag selector for your use case. app-inner { width: 100px } Commented Mar 4, 2020 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? Commented Mar 4, 2020 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). Commented Mar 4, 2020 at 17:33
  • @Shravan placing the class attribute directly (<app-inner class="inner-comp">) 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. Commented Mar 4, 2020 at 17:36
  • Setting the class directly in the child component tag appears to work. Take a look at this stackblitz. Commented Mar 4, 2020 at 17:39

1 Answer 1

5

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%; }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.