Veronika
Veronika

Reputation: 21

Mat-icon-button needs to be wrapped to apply density

When applying custom density (via a custom CSS class) using Angular Material Theme API directly to Angular Material button (e.g., mat-flat-button, mat-stroked-button), the height is adjusted as expected. However, when the custom density context (the same CSS class as for mat-stroked-button etc) is applied directly to a <button mat-icon-button>, the size of it remains unchanged. The density changes are only applied if the mat-icon-button is wrapped in an element with the density class.

/* Observe that the height changes as expected */
<button mat-flat-button class="ui-high-density">Some text</button>
/* Observe that the height does not change */
<button mat-icon-button class="ui-high-density">Some text</button>
/* Observe that the height changes as expected */
<div class="ui-high-density">
   <button mat-icon-button>
      <mat-icon>home</mat-icon>
   </button>
</div>

Css class:

.ui-high-density {
   @include mat.icon-button-density(-2);
}

Link to StackBlitz

Question: Why Angular Material mat-icon-button must be wrapped in other element to apply different density and other buttons such as mat-flat-button not?

Using Angular 18 and Angular Material 18 with Material Design 3

Upvotes: 2

Views: 87

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

The class that determines the dimensions is looking for the child element of high-density-class:

.high-density-class[_ngcontent-ng-c828002457] .mat-mdc-icon-button.mat-mdc-button-base[_ngcontent-ng-c828002457] {
    --mdc-icon-button-state-layer-size: 28px;
    width: var(--mdc-icon-button-state-layer-size);
    height: var(--mdc-icon-button-state-layer-size);
    padding: 2px;
}

As you can see, inside .high-density-class it looks for .mat-mdc-icon-button.mat-mdc-button-base since, both are at the root level, the styles do not get applied.

Whereas, if we have the class at the parent level, the child is found and the class is applied.

The CSS fix for this would be to simply follow the parent class approach, another fix might be to scope the mat.icon-button-density(-5) to the scope of the component.

// Apply density using the new API
.high-density-class {
  @include mat.button-density(-5);
}
:host {
  @include mat.icon-button-density(-5);
}

You can also add classes and scope this styling to a particular section, if you want to apply it to only a particular region.

You can raise a bug for this, maybe it will be fixed. The fix will be for .mdc-icon-button to have the height property defined on it, which is currently not.

Stackblitz Demo

Upvotes: 1

Related Questions