When and why should we use View Encapsulation in angular

后端 未结 2 785
一个人的身影
一个人的身影 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:29

    Let's take one example where we have one parent and one child component with their own html, ts, css files.

    Suppose in parent component's html you referenced child component like below-

    parent.component.html ->  
    

    Now, if you create and add any similar styles like parent.component.css file in child.component.css (let's take

    tag as an example) then those will get added to each component seperately even if all angular component's html gets rendered on single page. So now you will have seperate styles for

    in child component.(Behind the scene angular adds one random_atttr to each component and then to all elements inside that component)

    This behaviour of angular, comes in view encapsulation. Used by angular like shadow DOM techonlogy which is not supported by all broswers but angular does it like this. ViewEncapsulation has 3 options -

    encapsulation: ViewEncapsulation.None, 
               ViewEncapsulation.Emulated, (-- this is default)
               ViewEncapsulation.Native (-- only applies to browsers with shadow DOM technology)

提交回复
热议问题