1

I've been trying to style a BoxedComponent style from HeaderComponent without using ::ng-deep, but I'm not finding a way to so properly.

The BoxedComponent component class contains nothing different but a ViewEncapsulation.None.

@Component({
  selector: 'labs-boxed',
  templateUrl: './boxed.component.html',
  styleUrls: ['./boxed.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class BoxedComponent {}

HTML

<div class="boxed">
  <ng-content></ng-content>
</div>

I created two classes in its SCSS file to use everywhere, but I realized I couldn't still stylize the responsiveness of the component due to the same problem.

.boxed {
  /* rules */
}

.tall .boxed {
  height: 500px;
  width: 360px;
}

.squared .boxed {
  height: 340px;
  width: 340px;
}

In HeaderComponent's HTML file, I am making use of labs-boxed as follows:

<div id="who-we-are" class="d-flex justify-content-around">
  <labs-boxed [ngClass]="'tall'">
    <p>
    ...
  ...
...

So far it works, but then entering in the SCSS file, I have attempted many ways to access lab-boxed's styles and changing it:

.boxed { ... } .tall .boxed { ...}

and so on, but without success.

How can I do it, please?

1 Answers1

0

Since BoxedComponent has ViewEncapsulation.None all rules defined in boxed.component.scss becomes global. When HeaderComponent has default encapsulation, all rules defined in header.component.scss are isolated from global scope and becomes specific to HeaderComponent. As a matter of fact ng-deep works by making single rules global. In other words it removes rules from isolated scope and puts into the global scope and it is the only way of making a single rule global within an encapsulated styles file. Without help of ng-deep you can override child component styles in following ways;

  1. Apply another global style to child and add related styles to global; styles.scss file.

    • in header.component.html

    <labs-boxed class="custom-box-style">
    
    • in styles.scss

    .custom-box-style .boxed {
      // new rules
    }
    
  2. Programatically set styles on specific child instance.

    • in header.component.html

    <labs-boxed #childEl class="squared">squared and red</labs-boxed>
    
    • in header.component.ts

    @ViewChild('childEl', {read: ElementRef, static: true}) childEl: ElementRef;
    
    ngAfterViewInit() {
      const box = this.childEl.nativeElement.getElementsByClassName("boxed");
      box[0].style.backgroundColor = "red"
    }
    

Here is a demonstration of both approaches.

ysf
  • 4,634
  • 3
  • 27
  • 29