0

I'm using MatExpansionPanel from Angular Material. When I inspected the generated html I got something like this

<mat-expansion-panel _ngcontent-lnt-c367="" class="mat-expansion-panel ng-tns-c278-0 mat-expanded ng-star-inserted" ng-reflect-expanded="true">
   <div role="region" class="mat-expansion-panel-content ng-tns-c278-0 ng-trigger ng-trigger-bodyExpansion" id="cdk-accordion-child-0" aria-labelledby="mat-expansion-panel-header-0" style="visibility: visible;">
       <div class="mat-expansion-panel-body ng-tns-c278-0"> 
         ...
       </div>
   </div>
</mat-expansion-panel>

The first div (with the class mat-expansion-panel-content) has a lot of spacing that I want to remove. but before that I tried the css selector like the following

ion-menu mat-expansion-panel {
    background-color: green; /* works */
}
ion-menu mat-expansion-panel .mat-expansion-panel-content {
    background-color: red; /* doesn't work */
    margin: 0;
}

I tried inspecting the div to check if some other style uses !important I found out that my css is not present at all. Any clue why?

1 Answer 1

1

You have 3 methods you can use to access those inner css selectors inside other components.

Method 1 - global stylesheet

First you can give mat-expantion-panel a class name, then you can access that with your global .s(css) but i would only do that if its something you are gonna repeat.

example:

// component.html
...
<mat-expantion-panel class="bg-red">...</mat-expantion-panel>
...
// styles.scss (not component.scss)
mat-expantion-panel {
   &.bg-red {
     .mat-expansion-panel-content {
       background-color: red; /* should now work */
       margin: 0;
     }
   }
}

Method 2 - use ng-deep

use ::ng-deep, this means you bleed that css out into global space (breaking component styling isolation), so to avoid it changes something unintended use the pattern with the :host in you component.scss

Note: this is the preferred method. If you care about component isolation, cause then the style changes stays with component.

Example:

:host ::ng-deep {
  // you can no target the inner / generated css selectors from here.
  .mat-expansion-panel-content {
     background-color: red; /* should now work */
     margin: 0;
   } 
}

Method 3 - viewEncapsulation.none (rarely use / prefer not to)

Use Change the viewEncapsulation.none on your component. This means you bleed the entire css into the global space. Only usecases where i can come up with for a reason to use this if you make a UI library else i would not go with this approach

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.