Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class to the invoked Angular component itself? [duplicate]

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.

like image 945
CPHPython Avatar asked Oct 16 '25 04:10

CPHPython


1 Answers

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%; }
like image 129
CPHPython Avatar answered Oct 17 '25 17:10

CPHPython



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!