An awesome thing about building Angular components is that the styles you specify are 'local' to the component.
In normal HTML development, any style on the page can affect any other style. For example. If I add a style like this:
2 border:1px solid red;
3}
Every div in the site / application will have a solid red border. Check out a sample here.
If you build an Angular, component, and that style is only included in the application as part of the component, then only that component's div will given a solid color red border.
The reason for this is because Angular creates something they call a Shadow DOM. Under the hood it is some coding magic to conditionally apply styles only to the component in question, not to other components.
However, Angular allows us to change this behavior using something called ViewEncapsulation.
A default Angular component is like this:
2 selector: 'my-comp',
3 templateUrl: 'my-comp.component.html',
4 styles: [`my-comp.component.css`],
5 encapsulation: ViewEncapsulation.Emulated
6})
The Emulated value means that Angular will simulate a Shadow DOM. This is considered safest because not all browsers support their own shadow DOM trees.
In most cases, I use this approach and leave out the encapsulation attribute. I like to have my styles encapsulated to a single component. But that is not required. There are two other options:
2 selector: 'my-comp',
3 templateUrl: 'my-comp.component.html',
4 styles: [`my-comp.component.css`],
5 encapsulation: ViewEncapsulation.Native
6})
The Native property tells Angular to use the browsers Shadow DOM. In this case, styles are encapsulated just like they would be in the emulated approach. So, any styles in the my-com-componment.css file will affect all HTML elements globally.
To turn off style encapsulation complete, use the None value from the ViewEncapsulationclass:
2 selector: 'my-comp',
3 templateUrl: 'my-comp.component.html',
4 styles: [`my-comp.component.css`],
5 encapsulation: ViewEncapsulation.None
6})
I'm working on my second super really big Angular application for a client, and it is giving me the opportunity to touch on areas I normally wouldn't.