interview community logo

1
0
What is view encapsulation in Angular?
1 answer

What is view encapsulation in Angular?

Angular Robert Isaac asked 11 months ago


0

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

  1. ShadowDom this will use the browser's native Shadow DOM API to encapsulate CSS styles, this only works on modern browsers
  2. None this will disable the view encapsulation, which is highly not recommended
  3. Emulated this is default one, it will add random directives to your component elements and in the CSS selectors to achieve

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

  1. if you want to modify the style in your whole application, is to add this style in your styles.scss, since it's not related to a component its selectors won't be modified
  2. is to use ::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

Robert Isaac answered 11 months ago loading comments...