The big problem with the View Encapsulation in Angular ?

What is View Encapsulation?

View encapsulation defines whether the styles defined in the component should affect the whole application and vice versa.

View Encapsulation has three properties.

1) Emulated: The CSS written into the component should have scoped to that component only. The global CSS will affect the component in this case. This is the default behavior of View Encapsulation.

2) Native: The CSS written into the component should have scoped to that component only. The global css will not affect the component in this case.

3) None: The CSS written with the encapsulation none properties will propagate to the all the components. This means the if you have written some classes in the one component then it automatically accessible to all the components of the application.
@Component({
// ...
encapsulation: ViewEncapsulation.None,
styles: [
// ...
]
})
export class AppComponent {
// ...
}

The big Problem with the view encapsulation faces with the None properties.

Problem: When you use “none” property of view encapsulation all the classes of that component will automatically accessible across all the application. So if you by mistake used the same classes in both the component then it will apply the classes of the component which have encapsulation none properties.

Here is the example: https://stackblitz.com/edit/problem-with-view-encapsulation?file=src/app/app.component.ts

If you look at the above example I have given the same “home” class to the home component as well as app component. I have also used view encapsulation none property in the home component. So it will apply the same “home” class to both components.

The solution to this problem is to use the “main parent class” in all the components.

In the above Image, I have added the parent class “homecomponent” so it will help us to identify the classes used in the home component and will not apply directly to some other components.

Note: Make sure you define all the classes with parent class preceding it.

Happy Coding. ­čÖé

Front-end Developer. Passionate about designing, digital marketing, writing, and tea. You can connect with me on social media by links given below.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *