Angular - Emulated Encapsulation



ViewEncapsulation.Emulated

Emulated mode will change the styles in such a way that it only applies to the element inside the component only. However, global styles may still affect elements inside a component.

Example - Usage of Emulated Encapsulation

Let us create a simple component to check how ViewEncapsulation.Emulated mode works.

Step 1: Navigate to the project folder using cd command. Create a new component and name it view-encapsulation-sample.

ng generate component view-encapsulation-sample
CREATE src/app/view-encapsulation-sample/view-encapsulation-sample.spec.ts (675 bytes)
CREATE src/app/view-encapsulation-sample/view-encapsulation-sample.ts (271 bytes)
CREATE src/app/view-encapsulation-sample/view-encapsulation-sample.css (0 bytes)
CREATE src/app/view-encapsulation-sample/view-encapsulation-sample.html (41 bytes)

Step 2: Now, go to view-encapsulation-sample.ts file. Add ViewEncapsulation.None mode for the component as shown below −

view-encapsulation-sample.ts

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

@Component({
   selector: 'app-view-encapsulation-sample',
   imports: [],
   templateUrl: './view-encapsulation-sample.html',
   styleUrl: './view-encapsulation-sample.css',
   encapsulation: ViewEncapsulation.Emulated
})
export class ViewEncapsulationSample {

}

Step 3: Change the template, view-encapsulation-sample.html and add two containers as shown below −

view-encapsulation-sample.ts

<div>I am inside the none container</div>
<div class="mystyle">I am inside the none container and has my own style</div>

Here, the first container does not have any styles or class and it is more prone to get affected by the global styles. The second container has class attributes and yet has a chance to get affected by global styles.

Step 4: Apply the style in the component css file, view-encapsulation-sample.css as shown below −

view-encapsulation-sample.css

div.mystyle { color: brown }

Step 5: Add the component in the app component and app.html as shown below −

app.ts

import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ViewEncapsulationSample } from './view-encapsulation-sample/view-encapsulation-sample';

@Component({
   selector: 'app-root',
   imports: [RouterOutlet, ViewEncapsulationSample],
   templateUrl: './app.html',
   styleUrl: './app.css'
})
export class App {
   protected readonly title = signal('expense-manager');
}

app.html

<app-view-encapsulation-sample />
<router-outlet />

Step 6: Add a style in the global css assets, styles.css targeting div tag and run the application.

styles.css

div { color: blue }

Output

On running the application, you can the result as shown as below −

Emulated ViewEncapsulation Mode
Advertisements