Dynamically change background color of mat-expansion-panel-header based on whether or not it is expanded

Angular Material does add dynamic classes based on the expanding state.

mat-expanded would be the one you are looking for. The problem is this class gets also attached to the panel-content. In order to fix this, you can simply combine it with the .mat-expansion-panel-header class selector.

All summed up this would look like this:

.mat-expansion-panel-header.mat-expanded {
  background: red;
}

Notice: Angular Material does also add background: inherit on the hover state.

If that's not the behavior you want, simply overwrite it like this:

.mat-expansion-panel-header.mat-expanded,
.mat-expansion-panel-header.mat-expanded:hover {
  background: red;
}

You have to provide a CSS selector that is stronger than the default ones that are provided by angular material. This means including all the states where angular adds background-color: inherit:

.mat-expansion-panel-header.mat-expanded,
.mat-expansion-panel-header.mat-expanded:hover,
.mat-expansion-panel-header.mat-expanded:focus {
    background-color: red;
}