I am working on a project in angular, where I need to change the CSS class only for the current component. I am doing something like this:
selector: 'app-container',
templateUrl: './app.component.html',
styles: [
`.cd1-overe{
top: auto !important;
}
.cd1r .cd2{
top: 7rem !important;
}`
],
encapsulation: ViewEncapsulation.None
By doing this, the CSS is updated for all of the components, because this change is applied to global CSS.
2
Answers
Don’t set the encapsulation mode to
None
. With this and with the!important
modifier the component css rules are overriding the global css rules.Instead of this set the encapsulation mode to
Emulated
or just delete it (becauseEmulated
is the default). And in this case you won’t need the!important
modifier also.To change the CSS class only for the current component, use component-specific styles. By default, Angular encapsulates the styles within the component’s styles array, ensuring they do not affect other components.
Try the following steps to do it:
Remove the encapsulation:
ViewEncapsulation.None
line from your component decorator. This will revert to the default encapsulation mode, which isViewEncapsulation.Emulated
.Define your component with component-specific styles just like below:
By using this, the styles you define will only apply to the HTML elements within the
app-container
component, and won’t affect other components in your Angular application.You may not have to use the
!important
flag if you are not using any additional class or inline styles on the HTML side.