DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Trending

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Java Virtual Threads and Scaling
  • Unlocking AI Coding Assistants Part 2: Generating Code
  1. DZone
  2. Coding
  3. Frameworks
  4. What Is ViewEncapsulation in Angular?

What Is ViewEncapsulation in Angular?

In this article, we take a look at ViewEncapsulation and the Shadow DOM in Angular. Though it may sound a little sketchy, no need to worry. It's actually really helpful!

By 
Dhananjay Kumar user avatar
Dhananjay Kumar
·
Jun. 18, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
134.1K Views

Join the DZone community and get the full member experience.

Join For Free

To understand ViewEncapsulation in Angular, first, we should understand the Shadow DOM. You can learn in detail about the Shadow DOM here. Simply put, the Shadow DOM brings Encapsulation to HTML Elements. Using the Shadow DOM, markup, styles, and behaviors are scoped to the element and do not clash with other nodes of the DOM. The Shadow DOM is part of Web Components, which encapsulates styles and login of the element.

Angular Components are made up of three things:

  1. Component Class
  2. Template
  3. Style

The combination of these three factors makes an Angular component reusable across an application. Theoretically, when you create a component, in some way you create a web component (theoretically, Angular Components are not web components) to take advantage of the Shadow DOM. You can also use Angular with browsers, which does not support the Shadow DOM because Angular has its own emulation and it can emulate the Shadow DOM.

To emulate the Shadow DOM and encapsulate styles, Angular provides there types of View Encapsulation. They are as follows:

Let's try to understand it using an example. I have created a component, as shown below:

app.component.ts

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    title = 'parent component';
}

app.component.html app.component.css

h1 {
        background: red;
        color: white;
        text-transform: uppercase;
        text-align: center;
    }

We are setting the style of h1 in the component CSS. We have also created another component:

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

@Component({
    selector: 'app-child',
    template: `
  <h1>{{title}}</h1>
  `
})
export class AppChildComponent {
    title = 'child app';
}

In AppChildComponent, we are also using the h1 tag. To understand different ViewEncapsulation options, we will change the metadata of AppComponent.

Let us start with ViewEncapsulation.None, in this option:

  1. There is no shadow DOM.
  2. Style is not scoped to the component.

As you run the application, you will find h1 style has applied to both components, even though we only set style the in AppComponent. This happened because in AppComponent we have set the encapsulation property to ViewEncapsulation.None.

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    title = 'parent component';
}

In the browser, when you examine source code, you will find the h1 style has been declared in the head section of the DOM.

Therefore, in ViewEncapsulation.None, the style gets moved to the DOM's head section and is not scoped to the component. There is no Shadow DOM for the component and the component style can affect all nodes in the DOM.

Next, let us explore ViewEncapsulation.Native, in this option:

  1. Angular will create Shadow DOM for the component.
  2. Style is scoped to the component.

As you run the application, you will find the h1 style has applied to both components, even though we only set the style only in AppComponent. This happened because in AppComponent we have set the encapsulation property to ViewEncapsulation.Native, and we are using AppChildComponnet as a child inside the template of AppComponent.

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.Native
})
export class AppComponent {
    title = 'parent component';
}

In the browser, when you examine source code, you will a Shadow DOM has been created for the AppComponent and the style is scoped to that.

Therefore, in ViewEncapsulation.Native, Angular creates a Shadow DOM and the style is scoped to that Shadow DOM.

Next, let us explore ViewEncapsulation.Emulated, in this option:

  1. Angular will not create a Shadow DOM for the component.
  2. Style will be scoped to the component.
  3. This is the default value for encapsulation.
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent {
    title = 'parent component';
}

As you run the application, you will find that the h1 style from AppComponent is not applied to the h1 of the AppChildComponent. This is due to emulated scoping. In this, the style is scoped only to the component. In this option, Angular only emulates the Shadow DOM and does not create a real shadow DOM. Hence, the application that runs in browsers does not support a Shadow DOM also and styles are scoped to the component as well.

Let us see how Angular achieves this. In the browser, when you examine source code, you will find the answer.

Angular has created the style in the head section of the DOM and given an arbitrary id to the component. On basis of ID, selector style is scoped to the component.

These are three ViewEncapsulation options available in Angular. I hope you find this post useful. Thanks for reading. If you like this post, please share it.

AngularJS

Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!