htmlangularangular-material

Is it possible to style Mat-Checkbox to show an X instead of checkmark?


Trying to implement a functionality using Angular Material <mat-checkbox> where if the user clicks on a Yes Button, it shows a checkmark. If the user clicks No Button, it would show an X. I find Angular Material official guide a little vague on this I guess.

I have tried adding new 'X' svg as content inside mat-checkbox-background class but only works with encapsulation. I can not add in global as well because I have used <mat-checkbox> in other components too.I only want it to apply to one component.

 .mat-checkbox-background{
     content: url(/assets/icons/cancel_checkbox.svg) !important;
  }

Please give some suggestions Thanks!

Note: do not want to use encapsulation as it affects Other styles.


Solution

  • If I am getting it right, you want to show 'X' when it's un-checked. In that case, below CSS will be helpful:

    mat-checkbox.cross {
      .mat-checkbox-background {
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24px' viewBox='0 0 24 24' width='24px' fill='%23ff4081'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z'/%3E%3C/svg%3E");
        background-position: center;
        background-size: contain;
      }
    }
    

    You will need to use class with <mat-checkbox>:

    <mat-checkbox class="cross">...</mat-checkbox>
    

    I have also created a stackblitz: https://stackblitz.com/edit/angular-gyykpy?file=src/styles.scss