laprof
laprof

Reputation: 1354

How to add CSS for nested elements in Angular Material Design

For my app, I use the Angular Material Design to include the standard components. I ran into a problem that I noticed while redesigning the components. Most components from the Material Design lib include nested components. E.g. when I want to use the mat-expansion-panel, I do it as follows:

<mat-expansion-panel #panel hideToggle>
  <mat-expansion-panel-header>
    <div>Content</div>        
  </mat-expansion-panel-header>
</mat-expansion-panel>

The code above leads to the following code in the browser:

<mat-expansion-panel>
  <mat-expansion-panel-header>
    <span class="mat-content ng-tns-c145-72">  // Nested element
      <div>Content</div> 

Unfortunately, I don't have access to the nested objects from the template's stylesheet. This means that if I want to make the class="mat-content background blue, it does not work. The CSS is not applied to the nested element.

How can this be resolved? I could add the CSS in the root app, but that is very messy and leads to poorly maintainable code.

Upvotes: 0

Views: 866

Answers (1)

robbieAreBest
robbieAreBest

Reputation: 1771

If you do not want to add these rules to the parent sheet, you could use the ::ng-deep pseudo-class. I would suggest nesting it in the :host pseudo-class to limit your styling scope.

:host ::ng-deep {
  .mat-content {
    background: #59f;
  }
}

https://stackblitz.com/edit/angular-8hz1gx?file=src%2Fapp%2Fexpansion-overview-example.scss

Upvotes: 1

Related Questions