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

2

2

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>
Mazdaism answered 10/12, 2017 at 19:21 Comment(2)
Which file is that scss written in? It is probably because of encapsulationKania
it's in the scss file of the component that the template is inMazdaism
K
12

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.

Kania answered 13/12, 2017 at 7:11 Comment(0)
I
0

I'm answering this just because i had a lot of problem finding a solution for when you are trying to apply a style to an element translated with ngx-translate the class doesn't apply the css

//HTML
<p class="text" [innerHTML]="'your.tranlation.key' | translate"></p>

//translation keys
"key": "Lorem <span class='sub-text'>ipsum</span>"

Encapsulation is the solution. Hope this help the google search

Impact answered 7/2 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.