cssangularangular9angular2-hostbinding

How to add a class to the invoked Angular component itself?


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.


Solution

  • 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%; }