With Angular's newer MDC (16+) how do I change the color of a button?

330 views Asked by At

When Migrating to MDC-based Angular Material Components the classes in the Angular components no longer work to override the color of a material button.

Here is a working example of the issue: https://stackblitz.com/edit/c4vkb1?file=src%2Fexample%2Fbutton-example.html

This is because the material button has a Specificity of (0,2,0) (two classes), which is the same as the class in the angular component (.sample-color [_ngcontent-ng-c1823106284])

enter image description here

While I am aware of workaround (such as adding a tag to my CSS selector) I am hoping there are option options out there. Ideally, I would want the angular component classes of the same specificity to be of a higher precedence than the other CSS selectors in dependent libraries. (FYI I don't want to use !important)

2

There are 2 answers

1
Andrei On

in newer angular material versions they are working on design tokens. you can configure components way more than before with the tokens they provide. In your example instead of setting

color: white;

you can set

--mdc-text-button-label-text-color: white;

which would be treated by the component in a right way.


another solution would be to mark all the library styles with the help of relatively new api "css @layers".

 import '@angular/material/....theme.css' layer(library);

this way all of the styles from the library would work like if they had weaker selectors than your application selectors, because styles without layer are treated as stronger ones

0
AmitNayek On

we can create our won custom color with the disign patten as Angular material components follows - we just need to update the right css variable value associated with material class. Please look into below example for diffrent types of button we have added 'orange' color

Hare is example in :- https://stackblitz.com/edit/uwskwr?file=src%2Fexample%2Fbutton-overview-example.html

By forking to a new repository :- by default button text color set to 'white'
stackblitz:- strong text https://stackblitz.com/edit/uwskwr?file=package.json
repo:- https://github.com/Amit006/Angular-material-custom-color-buttons.git