Angular 2 to 8 override CSS styling with ViewEncapsulation

The common scenario every developer will face is that sometimes we have to override parent component css styling. But in angular the css we add will be scoped to each specific component. i.e whatever CSS we added for a component is scoped to ONLY that component. It will not be visible to outer Components or HTML tags outside that component.

In order to handle this situation angular came up with /deep/>>>, and ::ng-deep syntax in css.

However, in recent versions of Angular all 3 /deep/>>>, and ::ng-deep are deprecated. Now in order to override CSS styling. we have to use ViewEncapsulation property in the component.

Below are the 3 possible values to use to achieve different goals.

MemberDescription
EmulatedEmulate Native scoping of styles by adding an attribute containing surrogate id to the Host Element and pre-processing the style rules provided via styles or styleUrls, and adding the new Host Element attribute to all selectors.This is the default option.
NoneDon’t provide any template or style encapsulation.
ShadowDomUse Shadow DOM to encapsulate styles.For the DOM this means using modern Shadow DOM and creating a ShadowRoot for Component’s Host Element.

Lets go with an example.

 @Component({
  selector: 'my-app',
  template: `
    <h1>Hello World!</h1>
    <span class="red">Shadow DOM Rocks!</span>
  `,
  styles: [`
      h1 {
      color: blue;
    }
    .red {
      background-color: red;
    }

  `],
  encapsulation: ViewEncapsulation.None
})
class MyApp {
}

Here we added encapsulation: ViewEncapsulation.None property to the component so that the css we wrote for h1, .red class will be applied across the components. Since we are instructing angular that do not scope the css to this specific element. So all the css properties written in this component will bleed out of the component context and thus applied to html in other components.