0

I'm trying to override material UI checkbox css in my Home Component and it is working fine. But there are side effects like css of checkbox in form component is overriding. Can anyone suggest a solution for this.

HTML used

 <mat-checkbox formControlName="home">
  Home
</mat-checkbox>

css used for over riding by default it is grey color

::ng-deep .mat-checkbox .mat-checkbox-frame {
border-color: blue !important;
}

Form component mat checkbox - for this component also it is overriding border color to blue without writing any css

<mat-checkbox formControlName="form">
  Form
</mat-checkbox>

I believe this is happening due to usage of ::ng-deep

I even tried ViewEncapsulation also in the Home component. It is still overriding css in Form component and other css in both the components.

Any help regarding this would be appreciated.

1 Answer 1

4

To apply the style only inside a specific child component, add the :host selector to the following code in the CSS of that component:

:host ::ng-deep .mat-checkbox .mat-checkbox-frame {
  border-color: blue !important;
}

This will scope this rule to all checkboxes which are in this current component and all its children and will work pretty well in case of routed components.

But if you want to stick this css rule only for home page template then you can use:

home.component.css

.mat-checkbox ::ng-deep  .mat-checkbox-frame {
  border-color: blue !important;
}

Angular will replace it with:

.mat-checkbox[_ngcontent-rvb-c0] .mat-checkbox-frame {
    border-color: blue !important;
}

where _ngcontent-rvb-c0 is unique identifier of current compoent

Sign up to request clarification or add additional context in comments.

11 Comments

Wouldn't it is also override checkboxes in child components? Wouldn't be it better to use .mat-checkbox ::ng-deep .mat-checkbox-frame in home.component.css?
I meant using the code above in home.component.css (I will update the answer). According to my tests, we must also specify :home even if ::ng-deep is in the child CSS.
Yes, I understand that this code should go to home.component.css.
@yurzui - Was your suggestion about swapping ::ng-deep and .mat-checkbox? I haven't tried that (and my stackblitz is not configured for testing it).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.