What is view encapsulation in Angular?
view encapsulation is an Angular feature that prevent one component CSS from affecting other components
for example if you have two components both using h1
selector to give different style for h1
element, neither of them will overwrite the other as each of them will only affect its own component
angular view encapsulation has 3 values
for example this component
@Component({
selector: 'interview-community',
template: '<h1>Interview Community</h1>',
styles: [
`
h1 {
color: blue;
}
`,
],
standalone: true,
})
export class InterviewCommunityComponent {}
will generate this HTML
<interview-community _ngcontent-ng-c796481245="" _nghost-ng-c3868519496=""><h1 _ngcontent-ng-c3868519496="">Interview Community</h1></interview-community>
and this CSS
h1[_ngcontent-ng-c3868519496] {
color: blue;
}
that's why if there is another component has h1, it won't be affected since h1[_ngcontent-ng-c3868519496]
only matches h1 that has a directive _ngcontent-ng-c3868519496
while the other component will have a different random number
the downside of this is that if you are using a library and you want to modify the style of one of its component
but you have two solutions for this
styles.scss
, since it's not related to a component its selectors won't be modified::ng-deep
pseudo-selector if you want it to affect only one component, but you should always add :host
or any other selector before it, so it doesn't leak this style into other components, for example to modify Angular Material use:host ::ng-deep .mat-mdc-form-field-bottom-align {
display: none;
}
this will make sure that mat-mdc-form-field-bottom-align
class is only hidden in this component, you can instead of :host
to use mat-form-field
, since you are sure that mat-form-field
will only match those inside your component