Home > Enterprise >  How to override global style from a child component and scope the change only under that component i
How to override global style from a child component and scope the change only under that component i

Time:05-17

I have declared some css styling in global style.css file which is src/style.css in my angular project. In one of my component I want to override some styling and scope it only for that component. Currently, I can able to do that by using ::ng-deep, but, problem is, while I am changing global style from my child component using ::ng-deep it also alter the styling in global.scss as a result rest of my component also affecting for this. So what I want is, when I am changing this global style from that child component I just want to scope that change under that component.

The CSS class I declare in Src/Style.css is:

.main-content {
  width: 100%;
  padding: 24px;
}

I applied following attempts which did override the global styling, however, it also keep the change as a result other components also get affected by that change.

Attempt 1:

I apply encapsulation: ViewEncapsulation.None in the component and apply following in component scss file:

.main-content {
  padding: 24px 0px !important;
}

It worked, means, it does override the global style but the change doesn't scope only for this component.

Attempt 2:

I remove encapsulation for the component and apply ::ng-deep like below:

::ng-deep .main-content {
   padding: 24px 0px !important;
}

it also do the same as attempt 1.

Attempt 3:

I also found that if I use ::ng-deep with :host it scope the change only for that component. However, I couldn't able to make it working when I am using :host. Like the following piece of code doesn't do anything for my case:

:host ::ng-deep .main-content {
  padding: 24px 0px !important;
}

In this situation, how can I achieve overriding global css and scope it only for that component?

CodePudding user response:

I assume you're using .main-content in multiple places.

If that's the case, I'd avoid using ::ng-deep at all, removing it from your child component. Instead, I'd just add a new class to your .main-content element as follows:

.alternate-content {
   color: red;
}
<div ></div>

You won't need to use !important here either, because the selector is more specific.

CodePudding user response:

The simplest way is to use Javascript.

We assume that the main-content have id="main".

You just need to add this code in ngOnInit of the child component:

element: HTMLElement;

constructor(
  .
  .
  @Inject(DOCUMENT) private document: Document,
) { }

ngOnInit() {
   this.element = this.document.getElementById('main');
   this.element.classList.add('your-custom-class');
}

And in the ngOnDestroy() remove this class:

ngOnDestroy(): void {
   this.element.classList.remove('your-custom-class');
}
  • Related