Home > Enterprise >  Css from child component will affect the entire page
Css from child component will affect the entire page

Time:06-23

I have a page and the page is split in two. Part of the page is child1, part is child 2.

Hierarchy

Parent
   Child1
   Child2

Below are the css included in the page

Child1 ->   z-index: 1
Child2 ->   z-index: 2

I want to give a backdrop to the entire page when a button in child1 is clicked. Css is as follows

.backdrop {
    position: fixed;
    background-color: rgba(16,19,22,.6);
    z-index: 5;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

But this only takes up the child1 component. I want it to cover the entire page.

CodePudding user response:

EventEmitter

It is best to not fight against Angulars style encapsulation and just throw an event to the parent to let it handle the styling.

In your child component script:

@Output() styleEvent = new EventEmitter();

onClick() {
  this.styleEvent.emit();
}

Child component template:

<button (click)="onClick()">Add Style</button>

In the parent script:

styleOn = false

handleStyleEvent() {
  this.styleOn = !this.styleOn
}

getStyle() {
  return this.styleOn ? 'backdrop' : ''
}

In the parent template:

<div [ngClass]="getStyle()">
  <app-one (styleEvent)="handleStyleEvent()"></app-one>
  <app-two></app-two>
</div>

You can add the styling to your parent stylesheet (or styles.css if you want it to be globally available).

Here's an example on Stackblitz.

  • Related