Styling The Angular Material Input Form (Simple Guide)


The Angular Material library is awesome.

And with features like custom Material themes, form validation and custom errors it's no wonder developers love it.

😎 😎 😎

Sometimes when working with Angular Material there are times when you might want to adjust the styles of your mat-form-field to fit your design.

So today we'll get started by explaining how you can change the underline color of the input box when selected and remove the floating label.

coder

Changing the Underline Color on Selection

Angular Material’s form-field components can be difficult to style directly because of their encapsulated styles.

However, there are a few ways to get around this.

One approach is to increase the specificity of your CSS or apply styles at the global level.

Here's a simple example that changes the underline color when the input is selected:

::ng-deep .mat-form-field.mat-focused .mat-form-field-underline {
  background-color: #ff884d; // Desired color when input is focused
}

::ng-deep .mat-form-field-ripple {
  background-color: #ff884d; // Ripple effect color when focused
}

So what have we just done?

By using ::ng-deep this allows us to style encapsulated Angular Material components.

It's deprecated but still functional.

For a cleaner approach, you can use ViewEncapsulation.None at the component level, allowing for global styles without the need for ::ng-deep.

Here's how we do it.

@Component({
  /// other declarations here
  encapsulation: ViewEncapsulation.None
})

This allows global styles to override Angular Material's default styles.

Removing the Floating Label

We can remove the float label by using the floatLabel property and setting it to "never" or by removing the mat-label and using the placeholder attribute.

Here's an example:

<form class="search-form">
  <mat-form-field floatLabel="never" color="primary">
    <input class="toolbar-search" type="text" matInput placeholder="Search">
    <mat-icon matSuffix style="font-size: 1.2em">search</mat-icon>
  </mat-form-field>
</form>

Additional Styling Suggestions

To style other elements like the input text, you can modify classes like .mat-input-element. Here’s an example of changing the text color:

::ng-deep .mat-input-element {
  color: white;  // Changes input text color
}

Keep in mind that certain styles, like the underline or ripple effect, may need to be applied globally (in your styles.scss or global.scss), especially if you're using Angular's default view encapsulation.

So to finish, remember that Angular Material components can be tricky due to encapsulation, but by using the ::ng-deep selector or ViewEncapsulation.None, you can override the default styles and make the necessary changes.

If you want to learn more about styling the Angular Material input form you can check out the official API docs.

signature

Daniel Kreider