When and why should we use View Encapsulation in angular

后端 未结 2 782
一个人的身影
一个人的身影 2021-02-06 10:50

When working in angular is there a particular rule or guideline that should be used in deciding when to use and why to use View Encapsulation?

@Component({
    s         


        
2条回答
  •  天涯浪人
    2021-02-06 11:36

    Codecraft.TV has an amazing article on ViewEncapsulation that you can refer to get a better understanding.

    To just summarize it:

    ViewEncapsulation.Emulated: Angular changes our generic css class selector to one that target just a single component type by using automatically generated attributes.

    Any styles we define on a component don’t leak out to the rest of the application but with ViewEncapsulation.Emulated our component still inherits global styles.


    ViewEncapsulation.Native: If we want Angular to use the shadow DOM we can set the encapsulation parameter to use ViewEncapsulation.Native

    With ViewEncapsulation.Native styles we set on a component do not leak outside of the components scope.

    This is great if we are defining a 3rd party component which we want people to use in isolation. We can describe the look for our component using css styles without any fear that our styles are going to leak out and affect the rest of the application.

    However with ViewEncapsulation.Native our component is also isolated from the global styles we’ve defined for our application. So we don’t inherit the global styles and have to define all the required styles on our component decorator.

    Finally ViewEncapsulation.Native requires a feature called the shadow DOM which is not supported by all browsers.


    ViewEncapsulation.None: If we don’t want to have any encapsulation at all, we can use ViewEncapsulation.None.

    If we don't encapsulate anything, the style we defined in the component will leak out and started affecting the other components.

    Some other resources that you might want to have a look into:

    1. VIEW ENCAPSULATION IN ANGULAR - By Thoughtram
    2. View Encapsulation by Rangle.IO
    3. Scoping Your Styles in Angular With ViewEncapsulationView
    4. Diff between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated

提交回复
热议问题