How to change the style/theme of a single Component in Angular Material 15

216 Views Asked by At

I used the Angular Material Theming Guide (https://material.angular.io/guide/theming) to match the Style of components to our Branding. Now, I want to change a single instance of a (for exmaple) MatSelect. A MatSelect that is part of the Header and should be smaller than a regular MatSelect. Smaller in Dimension and smaller in Font Size. What is the official way of doing that?

Example:

  <div class="translator">
    <mat-select id="languageMenu" [(ngModel)]="selectedLang"
                (selectionChange)="changeLanguage($event)">
      <mat-option *ngFor="let lang of languages" [value]="lang.value">
        {{lang.viewValue}}
      </mat-option>
    </mat-select>
  </div>
1

There are 1 best solutions below

0
staschek On

You can now define the density:

@include mat.private-form-field-density(-2);

https://material.angular.io/guide/theming#customizing-density

And found that solution:

@use "sass:map";

/* Styles to be applied to buttons */
$my-custom-button: mat.define-typography-level(
  $font-family: 'Roboto',
  $font-weight: 500,
  $font-size: 2rem,
  $line-height: 1,
  $letter-spacing: 'normal'
);

/* Styles to be applied to input-fields */
$my-custom-input: mat.define-typography-level(
  $font-family: 'Roboto',
  $font-weight: 400,
  $font-size: 1rem,
  $line-height: 1,
  $letter-spacing: 'normal'
);

/* Merge custom configs into existing config */
$my-typography-config: map.merge(
    mat.define-typography-config(
        /* 'button'-property will work out of the box */
        $button: $my-custom-button
    ),
    (
        /* 'input'-property will have to be assigned under '@mixin typography' further below */
        'input': $my-custom-input
    )
);

/* Apply custom config */
@include mat.all-component-typographies($my-typography-config);

/* Let's assign the custom property 'input' that we defined above */
@mixin typography($theme) {
    $custom-typography-config: mat.get-typography-config($theme);
    
    .mat-mdc-form-field {
        @include mat.typography-level($custom-typography-config, 'input')
    }
}

/* Define custom app-theme based on custom-configs */
$app-theme: mat.define-light-theme(
    (
        typography: $my-typography-config,
    )
);

/* Apply custom app-theme */
@include typography($app-theme);

"Styling the buttons less complicated since $button is a default property in typography-config. Yet for the input-fields I needed to create a custom-property in typography-config and then manually assign it via @mixin to the class-selector of the material-input-fields (.mat-mdc-form-field)"