angularangular-material2

How can I change Angular Material button background color on hover state?


I have an Angular button:

<button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?


Solution

  • As of Angular 6, the use of /deep/ or ng-deep in the chosen solution is marked for deprecation. The recommended way is to use global styles as stated in the docs.

    Some Angular Material components, specifically overlay-based ones like MatDialog, MatSnackbar, etc., do not exist as children of your component. Often they are injected elsewhere in the DOM. This is important to keep in mind, since even using high specificity and shadow-piercing selectors will not target elements that are not direct children of your component. Global styles are recommended for targeting such components.

    In the specific case of button hover background, I had to use the following code in my styles.css (global stylesheet included via angular-cli or directly linked in index.html). Note that you might have to replace primary with accent or warn depending on the palette type (color="primary" or color="accent" or color="warn") used in the button.

    .mat-button.mat-primary .mat-button-focus-overlay {
      background-color: transparent;
    }
    

    If you don't want every button to be affected, it's better to have a specific class like no-hover-effect as shown below.

    .no-hover-effect.mat-button.mat-primary .mat-button-focus-overlay,
    .no-hover-effect.mat-button.mat-accent .mat-button-focus-overlay,
    .no-hover-effect.mat-button.mat-warn .mat-button-focus-overlay
    {
      background-color: transparent;
    }
    

    For every material button that doesn't need hover-effect, you'd do

      <button mat-button color="primary" class="no-hover-effect">
        No Hover Button
      </button>