Search code examples
angularangular-material

Proper way to add density to a single Angular Material (M3) component theme


Is the right way to add density to only form-field-theme in Angular v18 Material (M3) by redefining a theme specifically for it? The form fields are so comically large by default and we want them as density -4, but otherwise everything else is great at density 0 (default). Just seemed a bit awkward and I wasn't sure if this was bad practice, or would affect bundle size.

@include mat.core();

$_light-theme-properties: (
  color: (...),
  typography: (...),
);
$_light-theme: mat.define-theme($_light-theme-properties);

:root {
  @include mat.core-theme($_light-theme);
  //... Removed other components for brevity
  @include mat.button-theme($_light-theme);

  @include mat.form-field-theme(
    // Performs simple map.merge before define-theme
    mat.define-theme(add-theme-density($_light-theme-properties, -4)) // <----- ???
  );
}
// Included as a reference
@function add-theme-density($theme, $density) {
  @return map.merge(
    $theme,
    (
      density: (
        scale: $density,
      ),
    )
  );
}

Solution

  • this should work:

    html {
      @include mat.core-theme($app-theme);
      @include mat.all-component-themes($app-theme);
      @include mat.form-field-density(-4); // add this line
    }