Thursday, June 28, 2018

Encapsulation in Angular

CSS Encapsulation with Angular Components

If no encapsulation used than each component will have there own style and they will not affect others.

Global style defined in style.css and embedded in index.html are global for all components and will be applied to all.

If classes defined in child component have same style as in global css then child component style will be applied on child html.

We have an app component(parent) and two child component

import { Component } from '@angular/core';

@Component({
  selector: 'demo-app',
  template: `
    <h3>CSS Encapsulation with Angular</h3>
    <div class="cmp">
      App Component
      <first-cmp></first-cmp>
      <second-cmp></second-cmp>
    </div>
  `
})
export class App {
  constructor() { }
}


We link a separate style sheet into our index.html that has a single global style rule that will be applied to any element with the CSS class of cmp.


.cmp {
  padding: 6px;
  margin: 6px;
  border: 2px solid red;
}

There are three mode of Encapsulation
Emulated (default)
Native
None

1. Emulated (default)

When using this mode Angular will identify each component using two unique attributes: _nghost-* and _ngcontent-*. Any component styles will be added to the head using these attributes to isolate the styles as in the example below.

Create a different style for component which has used Emulated.

<head>
  <style>
    .container[_ngcontent-ikt-1] { ... } 
  </style>
</head>
<body>
  <my-app>
    <song-track _nghost-ikt-1>
      <div _ngcontent-ikt-1 class="container"></div>
    </song-track>
  </my-app>
</body>

Note the attributes added to the root and content of our component in bold. You can explicitly activate this mode by using the code below

@Component({
  selector: 'song-track',
  encapsulation: ViewEncapsulation.Emulated
})

2. Native

Turning on this feature will force browsers to use the Shadow DOM. For browsers that understand the Shadow DOM this creates a new rendering context for a given element that is completely isolated from the rest of the DOM. This is true native CSS encapsulation but it is not enabled by default in Angular. So lets look at the code and the generated output.

If we want that our component will not inherit styles from global style.css than use Native.

Create a completely different element using shadow dom and style so tag will not be affected by other styles.

Disable CSS Encapsulation

If you want to disable CSS encapsulation use ViewEncapsulation.None.

there are occasions where we would like a component’s CSS to not be encapsulated and apply globally to our application. Angular offers an easy way to disable CSS encapsulation. In this case  Child component style will overrride parent style.

So in case of style and element will not be updated they will remain same and get affected by last one defined.

No comments:

Followers

Link