Search code examples
angularsass

I'm having trouble with an scss selector that is nested in an ng-bootstrap tab


I have an angular project and created a component with scss settings that don't seem to select when I'm nesting the selector under ng-bootstrap tab class names. Why can't I use a selector like this .nav-link .badge in my scss? However something like .card-body .badge does select the element.

template file excerpt

 <ngb-tab id="projectInfoTab">
    <ng-template ngbTabTitle>
       Project info<span class="badge badge-pill badge-danger">4</span>
    </ng-template>
 <ng-template ngbTabContent>
...

scss

.nav-link .badge {
  margin-left: .5em;
}

Here's the rendered html

<div _ngcontent-c3 class="card-body">
  <a class="nav-link active" href="" role="tab" id="projectInfoTab" aria-controls="projectInfoTab-panel" aria-expanded="true" aria-disabled="false">
    Project info<span _ngcontent-c3="" class="error-badge badge badge-pill badge-danger">4</span>
  </a>
</div>

Solution

  • It is because of Angular encapsulation mechanism. When you create a component, it's encapsulation is Emulated by default.

    Check this link: Inspect generated css by Angular

    When you put your style in your component style file, angular will generate your style with some attributes added to it, so your custom style

    .nav-link .badge {
       margin-left: .5em;
    }
    

    will become something like following after compilation

    .nav-link[_ngcontent-c3] .badge {
       margin-left: .5em;
    }
    

    and since your ngb-tab component probably does not have any element with that attribute, it does not apply to it. You can change your component encapsulation by adding following code to your @Component decoration.

    @Component({
       selector: 'your-comp',
       ....
       encapsulation: ViewEncapsulation.None
    })
    

    Another thing you can do is to move this css to the ngb-tab component style file.