View Encapsulation In Angular

View Encapsulation In Angular

In Angular, view encapsulation defines how the styles defined in the template affect the rest of the app. While rendering the view ViewEncapsulation, angular employs three techniques. ViewEncapsulation is emulated. ViewEncapsulation and ShadowDOM None This article uses an example to explain what View Encapsulation is and how it is implemented in Angular. In Angular, we also learn about shadow dom.

The Angular framework allows us to define component-specific styles. This can be accomplished by using either inline style styles or the external style sheet style. URLs: in the @Directive decorator or @Component decorator.

Example of External Style sheet

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

Example of Inline style
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: ['p { color:blue}'],
})

CSS Styles have a global reach. The rules of CSS apply to the whole document. You are unable to apply rules to this section of the document. As a result, we use class, id, and CSS specificity requirements to ensure that the styles don't clash.

The components in Angular apps coexist with the other components. As a result, it's critical to make sure that the CSS Styles defined in one component don't conflict with the rules in another.

The View Encapsulation mechanisms are used by Angular to do this.

What is Encapsulation?

Encapsulation is a key notion in object-oriented programming (OOP). It expresses the concept of keeping all data and techniques that operate on that data private in a single unit (or class). It's as though the implementation detail is hidden from the rest of the world. The consumer of an encapsulated item is aware that it functions but is unaware of how it functions.

What is View Encapsulation in Angular ?

In Angular, the View Encapsulation approach governs how Angular hides (encapsulates) the styles set in the component from seeping into other areas of the application.

The three strategies listed below are offered by Angular to determine how styles are applied.
  1. ViewEncapsulation.None
  2. ViewEncapsulation.Emulated
  3. ViewEncapsulation.ShadowDOM

Since Angular 6.0.8, viewEncapsulation Native has been deprecated and replaced by viewEncapsulation ShadowDom.

Adding View Encapsulation to components

The @Component decorator's encapsulation metadata is used to add the Encapsulation methods, as seen below.

@Component({
  template: `<p>Using Emulator</p>`,
  styles: ['p { color:red}'],
  encapsulation: ViewEncapsulation.Emulated     //This is default
//encapsulation: ViewEncapsulation.None
//encapsulation: ViewEncapsulation.ShadowDOM
})

Example

Create an angular application with the help of the following command:

ng new encapsulation-demo

add the following code under the app.component.ts file:

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'View Encapsulation in Angular';
}

Open the app.component.html file and put the following code:

<h1>{{title}}</h1>
<p>I am a paragraph in green</p>

open the src/styles.css file and paste the following CSS into it.

p  {color: green;}

When you run the app, the paragraph should appear in green.

Check the elements area of the chrome developer tools. The CSS rules are placed in the page's head section.

View Encapsulation Example In Angular

ViewEncapsulation.None

The ViewEncapsulation is a container for views. When no encapsulation is desired, none is utilised. The styles defined in one component affect the elements of the other components when you use this.

Let's have a look at ViewEncapsulation now.

None of them do.

Add the following code to a new component called ViewNoneComponent.

import { Component,ViewEncapsulation } from '@angular/core';
 
@Component({
  selector: 'app-none',
  template: `<p>I am not encapsulated and in blue 
             (ViewEncapsulation.None) </p>`,
  styles: ['p { color:blue}'],
  encapsulation: ViewEncapsulation.None
})
export class ViewNoneComponent {
}

Encapsulation has been added: ViewEncapsulation. None. We've also specified the p color:blue inline style.

In AppModule, don't forget to import and declare the component. In app.component.html, you must additionally include the <app-none></app-none> selector.

<h1>{{title}}</h1>
<p>I am a paragraph in green</p>
 
<app-none></app-none>

When you run the code, both paragraphs turn blue, as expected.

This is due to the CSS styles' global scope. The ViewNoneComponent's style is injected into the global style, overriding any previously set styles. The styles.css style p colour: blue; overrides the styles.css style p colour: green;

ViewEncapsulation.None Example In Angular

The key points are as follows:
  • The component's styles have an impact on the other components.
  • The component's element styles are influenced by the global styles.

ViewEncapsulation.Emulated

We may easily add an id or a class to an element in an HTML page to boost the specificity of the CSS rules and prevent them from interfering with one another.

The ViewEncapsulation is a container for views.

To achieve encapsulation, the angular emulated technique adds distinct HTML characteristics to the component CSS styles and markup. This isn't the same as real encapsulation. The Emulated moniker comes from the fact that the Angular Emulates the encapsulation.

The ViewEncapsulation is used if you don't define encapsulations in components. A strategy that has been imitated

Create a new ViewEmulatedComponent component in your Angular app, as illustrated below:

import { Component,ViewEncapsulation } from '@angular/core';
 
@Component({
  selector: 'app-emulated',
  template: `<p>Using Emulator</p>`,
  styles: ['p { color:red}'],
  encapsulation: ViewEncapsulation.Emulated
})
export class ViewEmulatedComponent {
}

In the above component, no id has been added. The only difference between this component and one ViewNoneComponent is the encapsulation mode, which is ViewEncapsulation. Emulated

App.component.html should be updated using following code:

<h1>{{title}}</h1>
 
<p>I am a paragraph in green</p>
 
<app-none></app-none>
 
<app-emulated></app-emulated>

When you use mimicked mode, you can observe that the style does not flow over to other components. Angular adds _ngcontent-c2 properties to simulated components and performs required adjustments to the produced styles, for example.

By opening the chrome developer console, you may see this.

The _ngcontent-c2 attribute is added to both the style and the p element, making the style component-specific.

<style>p[_ngcontent-c2] { color:red}</style>

<app-emulated _ngcontent-c0 _nghost-c2>
    <p _ngcontent-c2>Using Emulator</p>
</app-emulated>

View encapsulation.emulated Example In Angular

The key points are as follows:
  • The component styles are separated using this method. They don't bleed into other parts of the system.
  • The component's element styles may be affected by global styles.
  • The attributes are added to the styles and markup by Angular.

ViewEncapsulation.ShadowDOM

The Shadow DOM is a DOM scoped sub-tree. It is attached to a DOM tree element called shadow host. When you navigate the main DOM, the shadow dom does not appear as a child node of the shadow host.

The shadow DOM is kept separate from the normal DOM by the browser. The Shadow DOM and the regular DOM are rendered independently. Before displaying it to the user, the browser flattens them out. The Shadow DOM's feature, state, and style remain private and unaffected by the main DOM. As a result, it achieves true encapsulation.

The Web Components standard includes the Shadow DOM. Shadow DOM isn't supported by all browsers. For the following examples, use Google Chrome.

All we have to do to make a shadow dom in Angular is add the ViewEncapsulation. The encapsulation strategy is ShadowDom.

Make a whole new component. Add the following code to ViewShadowdomComponent.

import { Component,ViewEncapsulation } from '@angular/core';
 
@Component({
  selector: 'app-shadowdom',
  template: `<p>I am encapsulated inside a Shadow DOM ViewEncapsulation.ShadowDom</p>`,
  styles: ['p { color:brown}'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class ViewShadowdomComponent {
 
}

As you can see, the component looks like this.

Viee Encapsulation.ShadowDOM Example In Angular

The component is rendered by angular inside the #shadow root element. The component's styles, as well as those from the parent and other components, are injected into the shadow root.

Shadow dom terminology

In the ViewShadowdomComponent, the CSS selector app-shadowdom is used. It was used in our app-component.html file. The component is rendered as a shadow dom and attached to the app-shadowdom selector by Angular. As a result, the element is known as the Shadow Host.

The #shadow-root element is the starting point for the Shadow DOM. As a result, we refer to this element as the shadow root. The Angular injects the component into the shadow root.

The #shadow-root is the starting point for the Shadow border. This element, including the node #shadow-root, is encapsulated by the browser.

The real encapsulation is archived in the shadow dom. It completely separates the component from the styles and the rest of the app.

The parent component's and sibling component's styles are still injected into the shadow dom. That, however, is an angular feature. The angular desires

The key points are as follows:
  • The genuine encapsulation is achieved via the shadow dom.
  • The component is still influenced by the parent and sibling styles. However, it is how Angular implements shadow dom.
  • All browsers do not currently support the shadow dom.

Conclusion

We discovered what view encapsulation is and how to apply the three different view encapsulation methodologies. None, Emulated, and ShadowDOM, to name a few. We'll look at how to style an Angular Component in the upcoming session.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post