Applying angular material theme to a specific component only

Viewed 4640

Is it possible to apply the angular material built-in theme to a specific component only?

I did:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

In one of my component.scss file and referenced this as the styleUrl inside of component.ts file. But the styles did not apply to my angular material paginator.

Here is what the paginator looks like

enter image description here

As shown, the styles do not apply.

Is it something to do with the fact that I'm importing them in a component specific scss file instead of importing it in angular.json?

2 Answers

You have to use the Mixins @angular/material provides instead of using a prebuilt theme.

@import '~@angular/material/theming';
@include mat-core();

// Use the desired palette
$palette:  mat-palette($mat-indigo);
// Create the theme
$theme: mat-light-theme($palette, $palette);

// Include component specific mixin
@include mat-dialog-theme($theme);

// Or wrap inside another selector to scope the styles to only one specific component
my-component {
   @include mat-dialog-theme($theme);
}

Edit: This code should be in your styles.scss (the global one, not the component specific scss)

The best way to make each component independent of default theme in angular is to having the import statement different for each component

As usual to have a default theme for overall application we can use that import (ex @import '@angular/material/prebuilt-themes/purple-green.css';) in the main css file which is style.css

After that for each component we can use the other themes based on requirement.

ex: for a component named homepage we can add a different theme to the file homepage.component.css

@import '@angular/material/prebuilt-themes/indigo-pink.css'; 

and for other component like login we add a different theme for the page login.component.css

@import '@angular/material/prebuilt-themes/pink-bluegrey.css';

This solved my issue.

Related